我相信你正在嘗試的是使用EXEC命令創建一個動態查詢。
您可以創建一個SQL語句,一個varchar變量,然後用EXEC執行它,在這裏從
https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/
如果你想要做這樣的事情
DECLARE @city varchar(75)
SET @city = 'London'
SELECT * FROM customers WHERE City = @city
這個例子節選是動態查詢創建。
DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand) --This does the magic
/*
just a heads up, the user impersonating the execution needs credentials for EXEC command.
*/
...將字符串值換成引號? –
沒辦法..我也試過'SELECT'和'SET' – mpsbhat