简体   繁体   English

基于查询列的动态Select查询 | SQL 服务器 2012

[英]Dynamic Select Query based on Query Column | SQL Server 2012

May I ask on how do we execute Dynamic Select Query?请问我们如何执行动态 Select 查询?

Basically what I want to achieve is a dynamic select that can SELECT a query based on a dynamic column, and that dynamic column is existing in a table.基本上我想要实现的是动态 select 可以 SELECT 基于动态列的查询,并且该动态列存在于表中。

Example Table示例表

Table Name: AppleBox
Table Columns: Apple101, Apple102, Apple103
Table Row: 
Apple101 = 1,2,3,4,5
Apple102 = 1,2,
Apple103 = 1

Supposed that I would run a query based on the example假设我将根据示例运行查询

SELECT apple+'$applecode' FROM AppleBox

with $applecode being from an external source, and $applecode = 101, and my expected query would be. $applecode来自外部源, $applecode = 101,我的预期查询将是。

SELECT apple101 FROM AppleBox

Is there a simple way to do this?有没有一种简单的方法可以做到这一点?

Please check below code.请检查以下代码。

CREATE TABLE [dbo].[AppleBox](
    [Apple101] [varchar](50) NULL,
    [Apple102] [varchar](50) NULL,
    [Apple103] [varchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[AppleBox] ([Apple101], [Apple102], [Apple103]) VALUES (N'1,2', N'1', N'1')
INSERT [dbo].[AppleBox] ([Apple101], [Apple102], [Apple103]) VALUES (N'3,4,5', N'1,2,', N'2')
INSERT [dbo].[AppleBox] ([Apple101], [Apple102], [Apple103]) VALUES (N'1,2,3,4,', N'1,2,3', N'3')
INSERT [dbo].[AppleBox] ([Apple101], [Apple102], [Apple103]) VALUES (N'1,2,3,4,5', N'1', N'4')


GO


DECLARE @query NVARCHAR(500)
DECLARE @exparam NVARCHAR(50)

SET @exparam='101'

SET @query='SELECT Apple'+@exparam+' FROM dbo.AppleBox'

EXECUTE sp_executesql  @query

You can use a case expression:您可以使用case表达式:

select (case when $applecode = 101 then apple101
             when $applecode = 102 then apple102
             when $applecode = 103 then apple103
        end) as apple
from t;

You would only need dynamic SQL (in this case) if your query could return a variable number of columns or if you wanted to set the name of the column.如果您的查询可以返回可变数量的列或者如果您想设置列的名称,则只需要动态 SQL(在这种情况下)。 Neither seems important.似乎都不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM