SQL Server 变量列名称? [英] SQL Server variable columns name?

查看:31
本文介绍了SQL Server 变量列名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么我不能像这样使用变量列名:

I am wondering why I cannot use variable column name like that:

declare @a as varchar;
set @a='TEST'

select @a from x;

谢谢

推荐答案

你不能这样做,因为 SQL 在它知道 @a 的值之前被编译(我假设实际上你希望 @a是一些参数,而不是像您的示例中那样硬编码).

You can't do it because SQL is compiled before it knows what the value of @a is (I'm assuming in reality you would want @a to be some parameter and not hard coded like in your example).

相反,您可以这样做:

declare @a as varchar; 
set @a='TEST' 

declare @sql nvarchar(max)
set @sql = 'select [' + replace(@a, '''', '''''') + '] from x'

exec sp_executesql @sql

但请注意,这是一个安全漏洞(sql 注入攻击),因此如果您不能信任或清理@a,则不应这样做.

But be careful, this is a security vulnerability (sql-injection attacks) so shouldn't be done if you can't trust or well clean @a.

这篇关于SQL Server 变量列名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆