SQL Server 中的动态查询 [英] Dynamic Query in SQL Server

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

问题描述

我有一个包含 10 列的表,如 col_1,col_2,.... col_10.我想编写一个 select 语句,该语句将选择行之一和这 10 列之一的值.我有一个变量来决定从哪一列中选择.可以在列名由变量动态决定的情况下编写这样的查询吗.

I have a table with 10 columns as col_1,col_2,.... col_10. I want to write a select statement that will select a value of one of the row and from one of these 10 columns. I have a variable that will decide which column to select from. Can such query be written where the column name is dynamically decided from a variable.

推荐答案

由于细节不够,无法给出代码.相反,我会解释.

Since I don't have enough details, I can't give code. Instead, I'll explain.

声明一个字符串变量,例如:

Declare a string variable, something like:

declare @sql varchar(5000)

将该变量设置为您想要的完整 SQL 字符串(作为字符串,而不是实际查询...因此您可以使用字符串连接嵌入您想要的行名称).

Set that variable to be the completed SQL string you want (as a string, and not actually querying... so you embed the row-name you want using string concatenation).

然后调用:exec(@sql)

一切就绪.

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

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