Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 为什么我需要“查询中的列值”的动态查询_Sql - Fatal编程技术网

Sql 为什么我需要“查询中的列值”的动态查询

Sql 为什么我需要“查询中的列值”的动态查询,sql,Sql,例如,这将从查询中返回一个值,然后将其用作列名 @A=Select top 1 productid from productlist order by timestamp desc 那么我想在另一个表中使用这个productid A Select @A from customerlist 然后结果是@A值,而不是customerlist中的字段值 当我使用动态查询时,我可以得到正确的结果。 为什么? 我知道我可以使用join,但是因为这个productlist表是动态的,所以让我们假设它是一

例如,这将从查询中返回一个值,然后将其用作列名

@A=Select top 1 productid from productlist order by timestamp desc
那么我想在另一个表中使用这个productid A

Select @A from customerlist
然后结果是@A值,而不是customerlist中的字段值

当我使用动态查询时,我可以得到正确的结果。 为什么?


我知道我可以使用join,但是因为这个productlist表是动态的,所以让我们假设它是一个子查询

您需要动态SQL,因为SQL不允许您使用参数作为列名或表名。只能对数据值使用参数,如where子句中的column1=@val

动态SQL是一种绕过这些限制的技巧,因为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,不同的数据库将使用不同但相似的语法。

1如果您的列实际上是数据字段,则您的数据模型有问题。2这需要动态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