多值参数的动态SQL错误

时间:2018-01-18 15:13:04

标签: c# sql-server-2012 dynamic-sql

我有一个包含动态SQL的存储过程,其中一个参数是多值的。执行时我收到以下错误:

错误消息:

GA'

附近的语法不正确

存储过程:

CREATE PROCEDURE [dbo].[usp_GetRepositoryReturnsGreaterThanZeroTest]    
                    @States varchar(max) = null
AS

Declare @filters varchar(max)

SET @filters = 'Where PaymentAmount > 0'

BEGIN  
SET @filters = @filters + ' AND (State in ('''+ @States + '''))'

DECLARE @SQLString varchar(max);
SET @SQLString = 'Select 
   [ID]
  ,[State]
 From dbo.Bil_ReturnsRepository ' + @filters

EXEC @SQLString

填充参数状态的C#代码:

 var statesList = "";
            foreach (var item in criteria.States)
            { statesList += string.Format("{0} '{1}'", statesList == "" ? "" : ",", item);}

            dbCommand.Parameters.Add(new SqlParameter("@States", SqlDbType.VarChar) { Value = statesList });

StatesList的值:

'GA', 'FL', 'TN'

1 个答案:

答案 0 :(得分:1)

乍一看我说行

'''+ @States + '''

因为这个 - 在你的例子中 - 将会导致

''GA', 'FL', 'TN''

尝试删除'''