如何创建一次指定的变量,然后在脚本中稍后用于查询中?这些变量可以在查询中多次使用,也可以在脚本中使用多次查询。在下面的例子中,我使用@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''以及其他答案的查询之一! –