例如,这从查询返回一个值,然后将其用作列名。
@A=Select top 1 productid from productlist order by timestamp desc
然后我想在另一个表中使用此“ productid” A
Select @A from customerlist
然后结果是@A值,而不是客户列表中的字段值。
使用动态查询时,可以获得正确的结果。 为什么?
(我知道我可以使用联接,但是因为此productlist表是动态的,所以我们假设它是一个子查询)
答案 0 :(得分:1)
您需要“动态SQL”,因为SQL不允许您将参数用作列名或表名。您只能将参数用于数据值,例如在where子句where column1 = @val
set @A = 'çolumn1'
Select @A from customerlist -- this fails because it is not allowed
动态SQL是绕开这些限制的“ hack”,因为SQL语句与参数所保存的任何值一起放置在字符串中。
set @A = 'çolumn1'
set @SQL = 'Select ' + @A + ' from customerlist;'
execute @SQL -- this works, the SQL statement is valid with no parameters as column names
以@SQL形式形成的字符串是完整的sql语句,不需要任何参数作为列名。
注意:我在这里使用的语法是不完整的,并且基于MS SQL Server,不同的数据库将使用不同但相似的语法。