我一直在努力处理下面的剧本,我无法找到更好的方法来做到这一点 有谁看到这个问题?我正确地声明了变量。为什么失败了?谢谢你的帮助!
DECLARE @var1 as VarChar(50)
DECLARE @var2 as VarChar(50)
SET @Var1 = '1, 2, 3, 4, 5'
EXEC('IF (select count(*) from Table1 where Column1 in (' + @Var1 + ')) = 5
SET @Var2 = ''True''
ELSE
SET @Var2 = ''False''')
SELECT @Var2
错误讯息:
必须声明SCALAR VARIABLE @ Var2
答案 0 :(得分:8)
如果您想从参数中获取值,则需要使用sp_executesql
。
要缩短查询,请使用CASE
。
DECLARE @var1 as VarChar(50)
DECLARE @var2 as VarChar(50)
SET @Var1 = '1, 2, 3, 4, 5'
SET @sqlCommand = 'SELECT @Var = CASE WHEN count(*) = 5 THEN ''TRUE'' ELSE ''FALSE'' END FROM Table1 where Column1 IN (' + @Var1 + ')'
EXECUTE sp_executesql @sqlCommand, N'@Var VARCHAR(5) OUTPUT', @Var=@var2 OUTPUT
SELECT @Var2
如果您想知道桌面上是否存在ID
的所有@Var1
,您还需要使用DISTINCT
SET @sqlCommand = 'SELECT @Var = CASE WHEN count(DISTINCT Column1) = 5 THEN ''TRUE'' ELSE ''FALSE'' END FROM Table1 where Column1 IN (' + @Var1 + ')'
答案 1 :(得分:4)
因为exec正在执行单引号内的SQL的动态部分。但是@ var2是在exec之外声明的。要解决此问题并在exec中选择@ var2或使用@ var2作为设置'+ @ var2 +'
答案 2 :(得分:2)
使用sp_executeSQL而不是exec并使用输出参数
E.g。 How to get sp_executesql result into a variable?
例如
DECLARE @var1 as VarChar(50)
DECLARE @var2 as VarChar(50)
DECLARE @ParmDefinition nvarchar(500);
SET @Var1 = '1, 2, 3, 4, 5'
SET @ParmDefinition = N'@Var2 VarChar(50) OUTPUT';
DECLARE @sSQL nvarchar(500);
set @sSQL = 'IF (select count(*) from Table1 where Column1 in (' + @Var1 + ')) = 5
SET @Var2 = ''True''
ELSE
SET @Var2 = ''False'''
EXEC sp_executesql @sSQL, @ParmDefinition, @Var2=@Var2 OUTPUT;
SELECT @Var2;
答案 3 :(得分:1)
那里有两件事......首先是“;”结束句子。您还需要scape varchar值。
同意其他答案...使用sp_executeSQL运行动态sql。
宣告的一个例子......
USE AdventureWorks2012;
GO
DECLARE @find varchar(30);
/* Also allowed:
DECLARE @find varchar(30) = 'Man%';
*/
SET @find = 'Man%';
SELECT p.LastName, p.FirstName, ph.PhoneNumber
FROM Person.Person AS p
JOIN Person.PersonPhone AS ph ON p.BusinessEntityID = ph.BusinessEntityID
WHERE LastName LIKE @find;
sp_executeSQL的一个例子..
DECLARE @IntVariable int;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
/* Build the SQL string one time.*/
SET @SQLString =
N'SELECT EmployeeID, NationalIDNumber, Title, ManagerID
FROM AdventureWorks.HumanResources.Employee
WHERE ManagerID = @ManagerID';
SET @ParmDefinition = N'@ManagerID tinyint';
/* Execute the string with the first parameter value. */
SET @IntVariable = 197;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@ManagerID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 109;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@ManagerID = @IntVariable;
答案 4 :(得分:0)
有许多理由不让执行sql字符串。我会改写这个:
declare @cnt int
select @cnt = count(1)
from Table1
where Column1 in
(select items
from dbo.Split(@Var1,',')
)
return @cnt -- then the calling function says if this is true or false.
对于Split函数,请参阅:HERE