我在sql server中创建了一个存储过程来馈送SSRS,以允许它接受多个值。我已经创建了它,当我在报表中使用它或在sql server中执行它时,出现以下错误消息。我有什么想念的吗?谢谢
Msg 207, Level 16, State 1, Line 35 Invalid column name 'London'.
这是我的示例数据。随时使用它创建表
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
这是我的动态存储过程代码
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
谢谢
EXEC dbo.CitiesGroup 'London'
错误的梅格
Msg 207, Level 16, State 1, Line 32 Invalid column name 'London'.
还有另一种方法可以做到这一点。为何不使用函数拆分参数,而不是将值传递给动态查询?
一旦选择了其中一个功能,就可以简单地重写存储过程,而无需在其中创建动态查询。
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
用法:
EXEC dbo.CitiesGroup 'London' GO EXEC dbo.CitiesGroup 'London,New York,Paris' GO