在 SQL 查询中动态选择列 [英] Dynamically choose column in SQL query

查看:64
本文介绍了在 SQL 查询中动态选择列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库字段名称调用 Code,我正在尝试使用如下变量名称选择它:

I have a database field name call Code and I am trying to select it using a variable name like this below:

Declare @var1 = [Code]

(SELECT @var1
 FROM [VoucherType]
 WHERE [DeletedBy] IS NULL
 AND [AutoID] = 1)

显然,SQL 会将 @var1 解释为字符串而不是我的数据库的字段,我怎么能这样做 @var1 被识别为字段名称 [Code] 而不是字符串,可能没有任何 select 或 if 语句.

Apparently, SQL will interpret @var1 as a string and not the field of my database, how can I do it in such a way @var1 is recognized as the field name [Code] instead of a string possibly without any select or if statements.

推荐答案

试试这个:

DECLARE @var1 VARCHAR(20)
DECLARE @sql VARCHAR(255)

SET @var1 = 'Code'
SET @sql = 'select ' + @var1 + ' from [VoucherType] where [DeletedBy] is null and [AutoID] = 1'

EXEC sp_executesql @sql

您必须编写一个动态查询,并使用 sp_executesql

You'll have to compose a dynamic query, and execute using sp_executesql

要在事物的动态"方面添加更多内容,请使用存储过程.请参阅此处的示例:

To add more on the 'dynamic' side of things, use stored procedures. See here for an example:

http://www.marten-online.com/database/execute-dynamic-sql-in-mssql.html

也就是说……如果您使用的是 Microsoft SQL SERVER

That is... if you are using Microsoft SQL SERVER

这篇关于在 SQL 查询中动态选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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