Stored Procedure with multi value parameter behaving strangely

穿精又带淫゛_ 提交于 2021-02-17 05:10:12

问题


I created a stored procedure in sql server to feed SSRS to allow it to accept Multiple values. I have created it and when I used it in my report or execute it in sql server I have the following error message. Is there anything i am missing? Thanks

Msg 207, Level 16, State 1, Line 35
Invalid column name 'London'.

This is my sample data. feel free to create table with it

DECLARE @MyTables AS TABLE (ID INT, City VARCHAR(100))
INSERT INTO @MyTables VALUES
(1,'London'),
(2,'Chester'),
(3,'Luton'),
(4,'New York'),
(1,'London'),
(2,'Chester'),
(5,'Paris'),
(5,'Paris'),
(2,'Chester'),
(2,'Chester')
SELECT * FROM @MyTables

This is my code for the dynamic stores procedure

CREATE PROCEDURE dbo.CitiesGroup
        @Cities NVARCHAR(Max) -- this are the parameters
    AS
    BEGIN
    DECLARE @sqLQuery VARCHAR(MAX)
    Declare @AnswersTempTable Table
    (  ID  INT,
       City VARCHAR(250)
    )
SET @sqlQuery =
    'SELECT  
    ID,
    City
FROM MyTables
where Convert(nvarchar(Max),City) IN ('+@Cities+')
Insert into @AnswersTempTable
exec (@sqlQuery)
select * from @AnswersTempTable'
END

Thanks

EXEC dbo.CitiesGroup 'London'

Error meg

Msg 207, Level 16, State 1, Line 32
Invalid column name 'London'.

回答1:


There is another way to do this. Instead of passing the values into a dynamic query, why not split the parameter using a function? This article written by Aaron Bertrand demonstrates different ways on how to split string in sql server.

Once you have selected one of the functions, you can simply rewrite your stored procedure without creating a dynamic query inside.

CREATE PROCEDURE dbo.CitiesGroup
    @Cities NVARCHAR(Max) -- this are the parameters
AS
BEGIN
    -- simplified query
    -- write your complex logic here
    SELECT ID, City
    FROM MyTables
    WHERE City IN (SELECT Item FROM dbo.SplitStrings_CTE(@Cities, N',');)
END

Usage:

EXEC dbo.CitiesGroup 'London'
GO

EXEC dbo.CitiesGroup 'London,New York,Paris'
GO

Useful Link:

Split strings the right way – or the next best way




回答2:


Alternatively, if you don't need to use a stored proc, you can simply put your query directly in the dataset as

SELECT ID, City
   FROM MyTables
   WHERE City IN (@Cities)

There is no need for dynamic sql as SSRS will do this for you. Just makes sure the SSRS parameter name and the Variable in your SELECT statement are identical (case-sensitive)



来源:https://stackoverflow.com/questions/49031223/stored-procedure-with-multi-value-parameter-behaving-strangely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!