0

May I ask on how do we execute Dynamic Select Query?

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.

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.

SELECT apple101 FROM AppleBox

Is there a simple way to do this?

pjustindaryll
  • 377
  • 3
  • 14

2 Answers2

1

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
Ketan Kotak
  • 942
  • 10
  • 18
  • What if Apple column will be expanded, is there a way for this to make it into a dynamic sql? – pjustindaryll May 18 '21 at 14:22
  • I didn't get your question. this @exparam will be your external parameter. it can be upto 123456789..... (n digits) as we have taken as nvarchar(50) length – Ketan Kotak May 19 '21 at 06:53
1

You can use a case expression:

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. Neither seems important.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • would there be a way for this? im worried because we might keep on expanding the SQL if there's more apple column to be added. :( – pjustindaryll May 18 '21 at 14:21
  • 1
    @pjustindaryll . . . Something is wrong with your data model if you are just adding new columns to a table. **These should be stored in separate rows.** – Gordon Linoff May 18 '21 at 18:19