2

i have a string with my needed columns, which i want to select. For example:

@sqlstring = 'col1,col2,col3'

I want select columns from table using this string. Like

SELECT @sqlstring FROM MyTable 

But choose only this string, as much as columns count in table

col1,col2,col3 
col1,col2,col3 
col1,col2,col3

3 Answers 3

2

You can try to use dynamic sql

DECLARE @SQL VARCHAR(MAX)=  'SELECT '+  @sqlstring + ' FROM MyTable '
EXEC (@SQL)  

SQLFIDDLE

Sign up to request clarification or add additional context in comments.

Comments

0

You need to use dynamic SQL. When doing so in SQL Server, I recommend using sp_executesql:

declare @sql varchar(max);

set @sql = '
select @sqlstring
from my_table
';

set @sql = replace(@sql, '@sqlstring', @sqlstring);

exec sp_executesql @sql;

Comments

0

In SQL Server 2016 they have introduced Split string function: STRING_SPLIT

DECLARE @sqlstring  varchar(100) = 'col1,col2,col3'
DECLARE @Delimiter CHAR = ','    
SELECT LTRIM(RTRIM(Split.a.value('.', 'VARCHAR(100)'))) 'Value' 
FROM  
(     
     SELECT CAST ('<M>' + REPLACE(@sqlstring, @Delimiter, '</M><M>') + '</M>' AS XML) AS Data            
) AS A 
CROSS APPLY Data.nodes ('/M') AS Split(a)

Comments

Your Answer

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.