Comma Delimiting Names with Apostrophes - sql

This is a T-SQL question.
I have a select statement where i take a list of cities and comma delimit them, then put them into a temp table. However, one of my cities is Couer D'Alene, which has an apostrophe in its name, and SQL is not liking that - no results are returned. How can I modify this to accept city names with apostrophes? Thanks!
Declare #vCity varchar(1000)
Select #vCity= ',' + #vCity+ ','
create table #Cities
(
cityName varchar (1000)
)
Insert Into #Cities
Select cityName
From cityTable
Where #vCity Like '%,' + cityName + ',%'
Group By cityName

You need to escape the ' with another ':''
Easiest way is the REPLACE function:
Select #vCity= ',' + REPLACE(#vCity,'''', '''''' ) + ','
All the extra ' are escaping several layers deep.

select QUOTENAME( cityName, '''' ) ...

Related

how to replace a comma with single quote comma in SQLIN clause

Hi all I have a an where clause like below
select * from table1
where colum1 IN (?parameter)
when I pass the values to the parameter they show up like below
('1,2,3') but to execute the query I need to change the values as ('1','2','3')
is there a way to replace the commas with single quotes comma in IN clause directly?
There is one hack to do what you want, using like:
select *
from table1
where ',' || column1 || ',' like '%,' || (?parameter) || ',%';
This functions, but it will not make use of an index on column1. You should think about other solutions, such as:
Parsing the string into a table variable.
Using in with a fixed number of parameters.
Storing the values in a table.
There may be other Oracle-specific solutions as well.
Use MS SQL, you can convert it into table value and using join for your condition, I am not familiar oracle but you can find same way to do it.
DECLARE #IDs varchar(max) ='1,2,3';
;WITH Cte AS
(
SELECT
CAST('<ID>' + REPLACE( #IDs, ',' , '</ID><ID>') + '</ID>' AS XML) AS IDs
)
SELECT '''' + Split.a.value('.', 'VARCHAR(100)') +'''' AS ID FROM Cte
CROSS APPLY Cte.IDs.nodes('/ID') Split(a)
You can achieve it using with clause. Logic here is to convert each comma separated value into different row.
with temp_tab as (
select replace(regexp_substr(parameter, '[^,]+',1, level),'''','') as str
from dual
connect by level<= length(regexp_replace(parameter, '[^,]+'))+1 )
select * from table1 where column1 in (select str from temp_tab);

SQL IN Statement splitting parameter

SQL Server
I have a parameter that contains a comma delimited string:
'abc,def,ghi'
I want to use that string in a IN statement that would take my parameter like this:
select * from tableA where val IN ('abc','def','ghi')
Any ideas on how I would do this?
If using dynamic SQL is an option, this can be executed:
SELECT 'SELECT * FROM tableA WHERE val IN (' +
'''' + REPLACE('abc,def,ghi', ',', ''',''') + ''')'
Basically, the REPLACE() function separates each item by ',' instead of just ,.
The simplest way would be to do something like this:
SELECT *
FROM TableName
WHERE ',' + commaDelimitedString + ',' LIKE '%,' + FieldName + ',%'
But be careful about SQL injection. You might want to parameterize it.
You can use this SQL to 'pivot' a comma-separated string into a table;
DECLARE #badData TABLE (id INT NOT NULL, txt NVARCHAR(max));
INSERT INTO #badData
VALUES (1, 'foo,bar,baz'), (2, NULL);;
-- the idea is to recursively 'pop' a value from the start of the string, splitting it into 'head' and 'tail' components
WITH unpacked (id, head, tail)
AS (
SELECT id, LEFT(txt, CHARINDEX(',', txt + ',') - 1), STUFF(txt, 1, CHARINDEX(',', txt + ','), '')
FROM #badData
UNION ALL
SELECT id, LEFT(tail, CHARINDEX(',', TAIL + ',') - 1), STUFF(tail, 1, CHARINDEX(',', tail+ ','), '')
FROM unpacked
WHERE tail > ''
)
SELECT id, head
FROM unpacked
ORDER BY id
You could stick this result into a common table expression, then write a where clause like
select * from tableA where val IN (select head from unpacked)
heavily plagiarised from https://stackoverflow.com/a/5493616/6722
Many programming languages have a split() function, for example in Ruby
'123,456,789'.split ","
=> ["123", "456", "789"]

How to wrap my query output with single quotation

I often read records from my database and use notepad++ to processing the receipt in this format:
'xxxxxxxxx'
'xxxxxxxxx',
'xxxxxxxxx',
'xxxxxxxxx'
Is there a way I can use SQL query to do this once.
Sample query I ran is:
Select ReceiptNo
from My_table
where TIN = 'KEYVALUE'
This is pretty straightforward concatenation. You need to use 4 quotes here, though: the first and last are your wrapper quotes which contain the string. The inner 2 quotes are your actual quote to use, and an escape quote.
SELECT
'''' + CAST(ReceiptNo as varchar(100)) + ''''
FROM
My_Table
WHERE
TIN = 'KEYVALUE'
You may want to try below:
SELECT
'''' + CAST(ReceiptNo as varchar(100)) + ''','
FROM
My_Table
WHERE
TIN = 'KEYVALUE'
SELECT ''''+ cast(ReceiptNo as varchar(10)) + ''',' as ReceiptNo
FROM My_table
WHERE TIN = 'T'
Here is my sql fiddle
You can use CONCAT function to append single quote. do like
SELECT concat( "'", DATEBASEFIELDNAME, "'" )

SQL Query to List

I have a table variable in a stored procedure. What I want is to find all of the unique values in one column and join them in a comma-separated list. I am already in a stored procedure, so I can do it some way that way; however, I am curious if I can do this with a query. I am on SQL Server 2008. This query gets me the values I want:
SELECT DISTINCT faultType FROM #simFaults;
Is there a way (using CONCAT or something like that) where I can get the list as a single comma-separated value?
This worked for me on a test dataset.
DECLARE #MyCSV Varchar(200) = ''
SELECT #MyCSV = #MyCSV +
CAST(faulttype AS Varchar) + ','
FROM #Simfaults
GROUP BY faultType
SET #MyCSV = LEFT(#MyCSV, LEN(#MyCSV) - 1)
SELECT #MyCSV
The last part is needed to trim the trailing comma.
+1 to JNK - the other common way you will see, which doesn't require a variable is:
SELECT DISTINCT faulttype + ','
FROM #simfaults
FOR XML PATH ('')
Note that if faulttype contains characters like "<" for example, those will be xml encoded. But for simple values this will be OK.
this is how we do this
create table #test (item int)
insert into #test
values(1),(2),(3)
select STUFF((SELECT ', ' + cast(Item as nvarchar)
FROM #test
FOR XML PATH('')), 1, 2, '')
Without the space after the comma it would be;
select STUFF((SELECT ',' + cast(Item as nvarchar)
FROM #test
FOR XML PATH('')), 1,1, '')

What is the best way to collapse the rows of a SELECT into a string?

In a SQL statement ( or procedure ) I want to collapse the rows of this table into a single comma delimited string.
simpleTable
id value
-- -----
1 "a"
2 "b"
3 "c"
Collapse to:
"a, b, c"
You can concatenate using an embedded 'set' statement in a query:
declare #combined varchar(2000)
select #combined = isnull(#combined + ', ','') + isnull(value,'')
from simpleTable
print #combined
(Note that the first isnull() initialises the string, and the second isnull() is especially important if there's any chance of nulls in the 'value' column, because otherwise a single null could wipe out the whole concatenation)
(edited code and explanation after comments)
Edit (ten years later):
SQL Server 2017 introduced the STRING_AGG() function which provides an official way of concatenating strings from different rows. Like other aggregation functions such as COUNT(), it can be used with GROUP BY.
So for the example above you could do:
select string_agg(value, ', ')
from simpleTable
If you had some other column and you wanted to concatenate for values of that column, you would add a 'group by' clause, e.g:
select someCategory, string_agg(value, ', ') as concatValues
from simpleTable
group by someCategory
Note string_agg will only work with SQL 2017 and above.
This will only work in MSSQL 2005+
select value + ',' from simpletable for xml path ('')
..one way to prevent the extra comma:
select case(row_number() over (order by id))
when 1 then value else ',' + value end
from simpletable
for xml path ('')
DECLARE #EmployeeList varchar(100)
SELECT #EmployeeList = COALESCE(#EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
SELECT #EmployeeList
Results:
1, 2, 4
This is based on #codeulike answer, but will prevent losing the portion of the string that gets concatenated before a null "value" is concatenated on.
declare #combined varchar(2000)
select #combined = isnull(#combined + ', ','') + ISNULL(value,'')
from simpleTable
print #combined