Sql server &引用;为变量赋值的SELECT语句不得与数据检索操作结合使用。”;关于SP中的变量
我的查询比我在这里发布的要复杂得多,但在使用Sql server &引用;为变量赋值的SELECT语句不得与数据检索操作结合使用。”;关于SP中的变量,sql-server,stored-procedures,dynamic-sql,Sql Server,Stored Procedures,Dynamic Sql,我的查询比我在这里发布的要复杂得多,但在使用sp\u executeSQL时,我无法使用变量。。。有解决办法吗 declare @system_status varchar(30) select @system_status = '12,20' declare @sql nvarchar(4000) select @sql = 'SELECT [system_status] FROM VW_Document_Main WHERE 1=1 ' IF @system_status IS
sp\u execute
SQL时,我无法使用变量。。。有解决办法吗
declare @system_status varchar(30)
select @system_status = '12,20'
declare @sql nvarchar(4000)
select @sql = 'SELECT [system_status]
FROM VW_Document_Main
WHERE 1=1 '
IF @system_status IS NOT NULL AND @system_status NOT IN ('-1','0')
BEGIN
SELECT @sql = @sql + 'and (',''+@system_Status+'',') LIKE ''%,''+system_Status+'',%'''
我试图将一个字符串连接到SQL的末尾,并最终使用sp_executesql
但是,我收到一条关于连接的错误消息:
不能使用为变量赋值的SELECT语句
与数据检索操作相结合
有没有关于如何修复/解决的想法
。。。。好吧,这太尴尬了,用SET代替SELECT工作得很好…您的动态sql构造函数有错误。我认为您在最后一行中需要的是:
SELECT @sql = @sql +
'and ('+','+@system_Status+',) LIKE ''%,'+
@system_Status+',%'''
选择@sql=@sql+
'和('+','+@system_Status+',)如'%,'+
@系统状态+',%''
您缺少一些引号:
declare @system_status varchar(30)
select @system_status = '12,20'
declare @sql nvarchar(4000)
select @sql = 'SELECT [system_status]
FROM VW_Document_Main
WHERE 1=1 '
IF @system_status IS NOT NULL AND @system_status NOT IN ('-1','0')
BEGIN
SELECT @sql = @sql + 'and ('','+@system_Status+','') LIKE ''%,''+system_Status+'',%'''
END
SELECT @sql
您的SELECT中的逗号有问题。我不完全确定你想做什么,所以我有两种可能的方法让它工作
1) 删除逗号
SELECT @sql = @sql + 'and ('''+@system_Status+''') LIKE ''%,''+system_Status+'',%'''
这使查询看起来像这样
SELECT [system_status]
FROM VW_Document_Main
WHERE 1=1 and ('12,20') LIKE '%,'+system_Status+',%'
SELECT [system_status]
FROM VW_Document_Main
WHERE 1=1 and (','+@system_Status+',') LIKE '%,'+system_Status+',%'
2) 添加更多引号,使逗号不在字符串之外
SELECT @sql = @sql + 'and ('',''+@system_Status+'','') LIKE ''%,''+system_Status+'',%'''
这使得输出像这样
SELECT [system_status]
FROM VW_Document_Main
WHERE 1=1 and ('12,20') LIKE '%,'+system_Status+',%'
SELECT [system_status]
FROM VW_Document_Main
WHERE 1=1 and (','+@system_Status+',') LIKE '%,'+system_Status+',%'
你标记了这个MySQL,但语法看起来像SQL Server,你能确认你正在使用的数据库吗?@bluefeet它必须是SQL Server
,因为nvarchar
很抱歉,它是SQL Server。请尝试使用SET
而不是SELECT
。@PolishPrince我同意,只是想确认一下。:)