如何在此查询中修复此SQL错误

时间:2009-06-02 19:49:48

标签: sql sql-server-2005

DECLARE @providerIdList varchar(400)
DECLARE @q varchar(400)

SELECT @q  =  ''

SELECT @providerIdList = '(1, 5, 15)'


SET @q = 'SELECT u.Id FROM [user] u
    LEFT JOIN Provider p ON u.Provider_FK = p.Id
    LEFT JOIN  Providers2Users pu ON pu.user_FK = u.Id 
    LEFT JOIN Provider ap ON ap.Id = pu.provider_fk
    WHERE p.Id  IN ' + @providerIdList




exec @q

以下是我尝试执行上面显示的查询时遇到的异常


Msg 203, Level 16, State 2, Line 18
The name 'SELECT u.Id FROM [user] u
    LEFT JOIN Provider p ON u.Provider_FK = p.Id
    LEFT JOIN  Providers2Users pu ON pu.user_FK = u.Id 
    LEFT JOIN Provider ap ON ap.Id = pu.provider_fk
    WHERE p.Id  IN (1, 5, 15)' is not a valid identifier.

如果有人能指出这些错误的原因我真的很感激

6 个答案:

答案 0 :(得分:8)

您正在寻找sp_executesql。这样做:

DECLARE @providerIdList nvarchar(400)
DECLARE @q nvarchar(400)

SELECT @q  =  N''

SELECT @providerIdList = N'(1, 5, 15)'


SET @q = N'SELECT u.Id FROM [user] u
    LEFT JOIN Provider p ON u.Provider_FK = p.Id
    LEFT JOIN  Providers2Users pu ON pu.user_FK = u.Id 
    LEFT JOIN Provider ap ON ap.Id = pu.provider_fk
    WHERE p.Id  IN ' + @providerIdList

exec sp_executesql @q

您现在正在尝试将该命令作为存储过程调用,但显然不是这样。 sp_executesql是一个系统存储过程,它允许您执行有效的SQL语句。系统存储过程位于主数据库FYI。

答案 1 :(得分:5)

您也可以使用

exec(@q)

这将执行文字字符串。

区别在于括号!

答案 2 :(得分:0)

您尝试执行无效的存储过程@q,请使用:

execute (@q)

答案 3 :(得分:0)

确定您使用NVARCHAR而不是VARCHAR。就在那时,您可以使用EXEC sp_executesql @q

答案 4 :(得分:0)

宣布@params NVARCHAR(4000)
声明@sql NVARCHAR(4000)

SET @providerIdList ='(1,5,15)'

SET @sql ='SELECT u.Id FROM [user] u LEFT JOIN Provider p ON u.Provider_FK = p.Id LEFT JOIN Providers2Users pu ON pu.user_FK = u.Id LEFT JOIN Provider ap ON ap.Id = pu.provider_fk WHERE p.Id IN'+ @providerIdList'

SELECT @params = N'@ providerIdList VARCHAR OUTPUT'

exec sp_executesql @sql,@ params,@ providerIdList = @ providerIdList

答案 5 :(得分:0)

或者根据您的代码显示,我根本不会使用动态SQL。如果可能,应避免使用动态SQl。

SELECT u.Id FROM [user] u    
LEFT JOIN Provider p ON u.Provider_FK = p.Id    
LEFT JOIN  Providers2Users pu ON pu.user_FK = u.Id     
LEFT JOIN Provider ap ON ap.Id = pu.provider_fk    
WHERE p.Id  IN (1, 5, 15)