• Here's an example of a parametrized dynamic query using sp_executesql. Note that I'm using the DelimitedSplitN4K to split the values because you can't use IN for a single variable with delimited values.

    DECLARE @Param nvarchar(4000)

    SET @Param = '12,15,32'

    --SELECT @Param = @Param + '''' + ParameterValue + ''''+ N', '

    --FROM ScriptParams WHERE scripttype='TestParam'

    --select @Param = substring( @Param, 1, (LEN( @Param)-1))

    DECLARE @sql nvarchar(max)

    set @SQL = 'SELECT Company_NO,

    '''' as CompanyName,

    CASE isNull(post_date, 0)

    WHEN 0 THEN DATEPART(yyyy, DATEADD(mm, - 6, create_date))

    ELSE DATEPART(yyyy, DATEADD(mm, - 6, post_date)) END AS Year

    FROM CompanyOrder

    CROSS APPLY dbo.DelimitedSplitN4K( @paramIN, '','')

    WHERE Item = CompanyType'

    EXECUTE sp_executesql @SQL, N'@paramIN nvarchar(4000)', @ParamIN = @Param;

    Even better would be to eliminate the dynamic code:

    SELECT Company_NO,

    '' as CompanyName,

    CASE isNull(post_date, 0)

    WHEN 0 THEN DATEPART(yyyy, DATEADD(mm, - 6, create_date))

    ELSE DATEPART(yyyy, DATEADD(mm, - 6, post_date)) END AS Year

    FROM CompanyOrder c

    WHERE c.CompanyType IN ( SELECT ParameterValue FROM ScriptParams s WHERE scripttype='TestParam')

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2