Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.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 server 使用COALESCE的动态sql中的变量表名_Sql Server_Stored Procedures_Prepared Statement_Dynamic Sql - Fatal编程技术网

Sql server 使用COALESCE的动态sql中的变量表名

Sql server 使用COALESCE的动态sql中的变量表名,sql-server,stored-procedures,prepared-statement,dynamic-sql,Sql Server,Stored Procedures,Prepared Statement,Dynamic Sql,我想以这种形式获取变量表的列col1,col2,col3 所以我使用了下面的查询 SELECT @cols = COALESCE(@cols + ', ', '') + column_name FROM INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG='mudb' and TABLE_NAME='mytbl' 我成功地完成了上述工作。但是当我想使用变量表名时。我有问题。我试过了 SELECT @cols = COALESCE(@cols + ',

我想以这种形式获取变量表的列
col1,col2,col3

所以我使用了下面的查询

SELECT @cols = COALESCE(@cols + ', ', '') + column_name FROM
INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG='mudb' and TABLE_NAME='mytbl'
我成功地完成了上述工作。但是当我想使用变量表名时。我有问题。我试过了

SELECT @cols = COALESCE(@cols + ', ', '') + column_name FROM
INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG='mudb' and TABLE_NAME=@tbl
但它给出的结果为空。然后我命令使用
EXECUTE sp\u executesql

set @FullStatement='SELECT @cols = COALESCE(@cols + '', '', '''') +
column_name FROM INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG=''mudb''
and TABLE_NAME=@tbl'

PRINT @FullStatement
EXECUTE sp_executesql @FullStatement

然后它给出了一个错误
必须声明标量变量“@cols”
,但是@cols已声明
@cols
可能在您正在运行的脚本范围内声明。它不在动态SQL的范围内声明。变量不会从一个级别继承到另一个级别

因此,您希望将其传递到执行环境中,您可以使用sp_executesql:

set @FullStatement='SELECT @cols = COALESCE(@cols + '', '', '''') +
column_name FROM INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG=''mudb''
and TABLE_NAME=@tbl'

PRINT @FullStatement
EXECUTE sp_executesql @FullStatement, N'@Cols varchar(8000) output, @Tbl varchar(8000)',
                      @cols = @cols, @tbl = 'MyTable';

这就是执行语句的工作方式。但是,这种连接列的方法在动态SQL中不起作用。

现在说\@tbl not delared,\@cols not delared。实际上,由于tbl错误,我只想用变量表名获得与第一个代码相同的输出。。我刚刚设置了@tbl='mytbl'(虽然存储过程已经收到了它的值,但它不起作用),现在我用第二个代码(动态表名)得到了结果