1

I am trying to create a query where the column are variable

Exp

Declare @parm1 int ;
Declare @param2 varchar(50) ;
Declare @param3 int ;
Select Id, name, age from @table_variable
Where
Id=@param1
Name= @param2
Age=@param3

instead of manually typing the columns I want to select each time, I want to replace "I'd, name, age" With an array

@column_array =[list of columns I want to select ] 

The list of columns is decided automatically from a winform app with check box list in visual studio that is variable in length, and values Is that even possible?

Dale K
28.1k15 gold badges59 silver badges85 bronze badges
asked Jul 27, 2019 at 20:11
5
  • No it is not possible , sql does not have arrays and you cannot select from variable. Commented Jul 27, 2019 at 20:34
  • 1
    SQL Server does not support macro substitution... this leaves dynamic SQL Commented Jul 27, 2019 at 21:02
  • You can execute sql queries you build yourself...basically build a string, and execute it with sp_executesql Commented Jul 27, 2019 at 21:03
  • The problem with dynamic SQL here, is you'd have to pass all your input values as a varchar, which is less than ideal. Commented Jul 27, 2019 at 21:03
  • Simply build the SQL statement in the application code using the list of selected columns and execute the query. No need to use T-SQL for the task. Commented Jul 27, 2019 at 22:18

1 Answer 1

1

No you cannot use a variable in that way. You can however use a variable to build the statement dynamically and execute the statement like so: The code assumes that @col1, @col2 and @table_variable have been declared and assigned values.

Declare @tsql varchar(2500);
Set @tsql = ‘ select ‘;
Set @tsql += @col1 +’, ‘;
Set @tsql += @col2;
Set @tsql ‘ from @table_variable;’
Print @tsql;
Exec (@tsqll);
sticky bit
37.7k12 gold badges34 silver badges46 bronze badges
answered Jul 27, 2019 at 22:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.