Link to home
Start Free TrialLog in
Avatar of Member_2_1242703
Member_2_1242703

asked on

Adding quotes to SQL SELECT result based on original value

In an SQL SELECT statement, how would I get any value that contains a comma, to surround the entire value in quotes?
i.e.

Value is 123 Maple St., Apt 1
Would be "123 Maple St., Apt 1" in the result set
Avatar of Deepak Chauhan
Deepak Chauhan
Flag of India image

Are you looking something like this.

select '"' + column +'"' from Table where column  like '%,%'
Rather than being inconsistent and having quotes around data in some records and not others, put them around the data in every row:

Select '"' _ address + '"' as Address from table Where [condtion]

in the above, it does not display well.  '"' is a single quote followed by a double quote, followed by a single quote or spaced out -   '  "  '
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you really need quote only around the value if there is a comma then look at this:

This bit of SQL shows how to use Charindex

Declare @mainString nvarchar(100)='john, john'  
 
if CHARINDEX(',,',@mainString) > 0  
begin  
   select 'found' As Result  
end  
else  
    select 'Not found' As Result  

Then wrapping it up in a CASE statement, you get what you asked for:

Declare @mainString nvarchar(100)='contains, a comma'  
select case  CHARINDEX(',',@mainString) WHEN 0 THEN '"' + @mainString + '"' ELSE @mainString END

or

Declare @mainString2 nvarchar(100)='no comma'  
select case  CHARINDEX(',',@mainString2) WHEN 0 THEN '"' + @mainString2 + '"' ELSE @mainString2 END
... someone beat me to it
Avatar of Member_2_1242703
Member_2_1242703

ASKER

John, I actually like your initial thought and just implemented it. I got to thinking though, that I really probably need to cover multiple columns, (despite my not clarifying in my OP.) Playing around with the CASE now
Please try this.- this should fix all your problems.

FourSingle quotes + 1 doublequote + yourcolumnName + 1 doublequote  + 4singlequotes

SELECT 
CASE 
	 WHEN CHARINDEX(',',yourcolumn,0) = 0 THEN yourcolumn 
	 ELSE
		 '''' + '"' +  yourcolumn + '"' + '''' 
	 END
		as yourcolumn
FROM tableName

Open in new window

or

SELECT '''' + '"' +  yourcolumn + '"' + '''' as yourcolumn
FROM tableName
WHERE yourcolumn LIKE '%,%'

Open in new window

edited my last post. pls try.
I always hate messing around with how many single quotes, so I use the ascii values -
select char(34) + yourvalue + char(34) from yourtable where charindex(",",yourvalue) > 0
What do you mean when you say you need to cover multiple columns?
Thanks!!!