-1

For instance I have a string parameter @p_colors with a value like:

'yellow','blue','red'

which is passed into a stored procedure. And when I try to select it like this:

EXECUTE(CONCAT('SELECT ', @p_colors));

The result is the values are selected by columns.

No column name | No column name | No column name
------------------------------------------------
Yellow         | Blue           | Red

How will I do it if I want to display them by row like this:

No column name |
----------------
Yellow         |
----------------
Blue           |
----------------
Red            |
----------------

using only the string formatted parameter. Is there any way in SQL to make this?

EDIT:

The actual result will be inserted into a temp table so the actual code is :

EXECUTE('INSERT INTO #colors(color) SELECT ', @p_colors);
Red Magda
  • 398
  • 4
  • 17
  • @zoharpeled The question seems to be different? – neer Apr 29 '17 at 07:35
  • Downvote reason: not even minimal reaserch. a simple search for "split strings sql server" would give you 478,000 on google, and 841,000 on Bing. – Zohar Peled Apr 29 '17 at 07:35
  • @Neer how is it different? It's a simple string split question. – Zohar Peled Apr 29 '17 at 07:35
  • As a parameter and want to run it – neer Apr 29 '17 at 07:36
  • @NEER I'm not following. Why is splitting a hard coded string should be different then splitting a string inside a parameter? It's the same thing – Zohar Peled Apr 29 '17 at 07:38
  • I do not agree with you. – neer Apr 29 '17 at 07:41
  • That I understand, what I don't understand is **why**. You can vote to reopen, but if you can provide a good reason why it's different then any other string splitting scenario I'll be happy to revoke my close vote. – Zohar Peled Apr 29 '17 at 07:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142955/discussion-between-neer-and-zohar-peled). – neer Apr 29 '17 at 08:01

1 Answers1

1

You can as the below:

SELECT * FROM (VALUES('yellow'), ('blue'), ('red')) t(c)

Update:

DECLARE @Param NVARCHAR(MAX) = '''yellow'', ''red'', ''blue'''
DECLARE @Query NVARCHAR(MAX) 
SELECT @Query = 'SELECT * FROM (VALUES(' + REPLACE(@Param, ''',', '''),(') + ')) t(c)'
--SELECT @Query
EXEC sp_executesql  @Query
neer
  • 4,031
  • 6
  • 20
  • 34