Place quotes & add comma around many items in WHERE

258 Views Asked by At

I have a very long list of codes for a WHERE statement in SQL Server that I would like to 'quickly' add quotes around each one and a comma at end of each one.

I would like to take the huge list like this (with 100's of them in my WHERE)

WHERE CODE IN 
(P279273
Q2793567
Q29262718)

and 'quickly' insert quotes and commas like this (doing it directly in SQL)

WHERE CODE IN
('P279273',
'Q2793567',
'Q29262718')

Anyone know how to insert those in quickly in SQL Server directly without manually going line by line (and not doing it in Excel first)?

2

There are 2 best solutions below

4
John Cappelletti On BEST ANSWER

Just another option

Example

Declare @S varchar(max) = 'P279273
Q2793567
Q29262718
Q99999
Q00000
'

Select string_agg(v,',')
 From (
        Select v=concat('''',replace(value,char(13),''),'''')
         From string_split(@S,char(10))
         where value<>''
      ) A

Results

'P279273','Q2793567','Q29262718','Q99999','Q00000'
4
2189490 On

First get a line-separated list of your elements.

  1. If you use visual studio code/azure data studio, you can use Ctrl + Alt (Shift + Alt for Visual Studio/SSMS) and down arrow to make multiple cursors for each line.
  2. Once you see a cursor for each line, insert your single quote.
  3. Hold Ctrl and press the right arrow (or End if one or more lines has spaces in the words) to move to the right side of the keyword. Insert another single quote and a comma.
  4. Delete the comma on the last line. Cut and paste the list into your WHERE IN ()

Article on this - https://www.sqlservercentral.com/blogs/quick-tip-quickly-bulk-edit-lines-in-ssms