在MS SQL Server Management Studio 2005中,运行以下代码
EXEC('SELECT * FROM employees WHERE employeeID = ' + CAST(3 AS VARCHAR))
出现此错误:
Incorrect syntax near 'CAST'
但是,如果我这样做,它会起作用:
DECLARE @temp VARCHAR(4000)
SET @temp = 'SELECT * FROM employees WHERE employeeID = ' + CAST(3 AS VARCHAR)
EXEC(@temp)
我在这里找到了一个解释:
T-SQL: Cannot pass concatenated string as argument to stored procedure
根据公认的答案,
EXEC
可以将局部变量或值作为其参数,但不能将其作为表达式。
但是,如果是这样,为什么这样做:
DECLARE @temp VARCHAR(4000)
SET @temp = CAST(3 AS VARCHAR)
EXEC('SELECT * FROM employees WHERE employeeID = ' + @temp)
'SELECT * FROM employees WHERE employeeID = ' + @temp
当然,在我看来这是一个表达式,但代码执行时没有错误。