如何創建一次指定的變量,然後在腳本中稍後用於查詢中?這些變量可以在查詢中多次使用,也可以在腳本中使用多次查詢。在下面的例子中,我使用@x
作爲這樣一個變量。SQL將變量添加到查詢中
我想要做的是一樣的東西:
Declare @Query nvarchar(1000)
Declare @x nvarchar(40)
Set @x = 'test'
Set @Query = 'Select [Name]
, ' + @x + ' as [TestCase]
From mytable'
Exec (@Query)
-- returns "Invalid column name 'test'"
它返回上面提到的錯誤。我想它實現相當於:
Declare @Query nvarchar(1000)
Declare @x nvarchar(40)
Set @x = 'test'
Set @Query = 'Select [Name]
, ''test'' as [TestCase]
From mytable'
Exec (@Query)
-- Returns e.g.
-- Name TestCase
-- Alice Test
-- Bob Test
我也注意到以下不工作,並返回相同的錯誤第一:基於錯誤,因爲我
Declare @Query nvarchar(1000)
Declare @x nvarchar(40)
Set @x = 'test'
Set @Query = 'Select [Name]
, ' + 'test' + ' as [TestCase]
From mytable'
Exec (@Query)
-- returns "Invalid column name 'test'"
我沒有試圖使用@x
作爲列名,而只是作爲一個變量,我假設我正在使用變量的無效實現。
哦,非常好,謝謝!這按預期工作。 – conor
接受這個答案,因爲它最徹底地回答我的問題,並簡化它 - 在這種情況下,我實際上並不需要動態SQL。 – conor
我很高興它有幫助。要回答你的問題的後半部分,你可以嘗試'select @ query'來查看正在組成的查詢。你會看到'select [Name],test as ...'將「test」視爲列名。你需要用引號包裝 - 正如其他答案顯示的那樣。但是接下來你會介紹「如果@ x引用了它會發生什麼事情」的問題,這說明了動態SQL的危險。例如,嘗試'set @x ='test'',Name,Name,Name,''hahaha''以及其他答案的查詢之一! –