Creating a dynamic where clause in SQL Server stored procedure

后端 未结 1 1422
一个人的身影
一个人的身影 2021-01-25 04:43

I am trying to create a stored that will accept two values, a column name and a value. It will then check if there is a record that exists for the passed in column name with the

相关标签:
1条回答
  • 2021-01-25 05:11

    At least one issue: you should be surrounding your string value with single quotes, and to escape those inside a string you need to double them up:

    WHERE ' + @pi_colName + ' = ''' + @pi_colValue + ''' AND ...
    

    You also may want to declare your @sql variable as something bigger than 100 characters! Looks like your string is getting truncated.

    If the possible values for @pi_colName are finite, the data type is always string, and the columns are collation compatible, you could do something like this and avoid dynamic SQL:

    SELECT ...
    WHERE CASE @pi_colName 
      WHEN 'col1' THEN col1
      WHEN 'col2' THEN col2
    END = @pi_ColValue;
    
    0 讨论(0)
提交回复
热议问题