Search code examples
sqlsql-serverstored-proceduressql-server-2000

Multiple Values are not inserting


Using SQL Server 2000

I want to select the id according to the department

ID Department
001 H001
002 F001
003 S001
004 D001

Stored procedure

ALTER  PROC [dbo].[proc_Atnd1] 
@Dep VARCHAR(100)
AS
BEGIN
DECLARE @SQL VARCHAR(1000)
DECLARE @Flag INT
SELECT @Flag=0
SELECT @SQL = 'SELECT ID FROM Table1 WHERE '
IF @Dep <>'All'
BEGIN
IF @Flag=1 
BEGIN
SELECT @SQL = @SQL+' AND (DEPARTMENT IN ('''+@Dep+'''))'
END
ELSE
BEGIN
SELECT @SQL = @SQL+' (DEPARTMENT IN ('''+@Dep+'''))'
SELECT @Flag=1
END
END
if @SQL = 'SELECT ID FROM Table1 WHERE ' SELECT @SQL = 'SELECT ID FROM Table1'
Delete from tb_Sample
INSERT INTO tb_Sample EXEC(@SQL)
end

This stored procedure is working for individual or all departments, but it is not working for multiple departments.

  • If I pass the value to stored procedure All means, it is displaying all the id for that department
  • If I select H001 means, it is displaying id for the H001 department.
  • If I select H001 and D001 means, nothing displaying.

I am passing a value for multiple departments like this H001,D001,F001 to the stored procedure. But stored procedure is not inserting an id for the selected department

What is the problem with my stored procedure?

Need stored procedure help


Solution

  • First, I wouldn't recommend building up dynamic SQL statements like this... it can make you vulnerable to SQL injection attacks. If you have to pass in a string with a comma-separated list, I would instead parse through that list and insert each individual value into a temporary table. From there you can join to the temporary table instead of using an IN statement.

    However, the problem here is that you're surrounding the comma-separated list with quotes, so instead of looking for the values H001, D001, and F001... it's looking for a single value equal to 'H001', 'D001', 'F001'

    To fix your issue, you would change your select statement to:

    SELECT @SQL = @SQL+' (DEPARTMENT IN ('+@Dep+'))'
    

    And when you pass in the comma-separated list, wrap each individual value in quotes within the string like this:

    EDIT: Changed from variable assignment to stored procedure call to make it more clear what I'm suggesting.

    exec dbo.proc_Atnd1 '''H001'', ''D001'', ''F001'''
    

    Something that is helpful when troubleshooting these types of issues is to PRINT out the SQL that you've created, and then examine it and make sure it is doing what you expect.

    But again, I would suggest that you not take this approach and instead look into parsing the list and avoid dynamic SQL.