How can I insert an single quotes in a query ?
Example
select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES
(' + CAST(Endereco_Id as varchar) + ','
+ CAST(Logradouro_Id as varchar) + ','
+ CAST(Bairro_Id as varchar) + ','
+ CAST (CEP as varchar) + ','
+ CAST(Logradouro as varchar) + ','
+ CAST(Livre as varchar) + ')' as teste
FROM San_Endereco
Before each CAST I need put the single quote. How can I do that ?
Use two single quotes: ''
select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES
(''' + CAST(Endereco_Id as varchar) + ''','''
+ CAST(Logradouro_Id as varchar) + ''','''
+ CAST(Bairro_Id as varchar) + ''','''
+ CAST (CEP as varchar) + ''','''
+ CAST(Logradouro as varchar) + ''','''
+ CAST(Livre as varchar) + ''')''' as teste
FROM San_Endereco
Use double single quotes ''
If a single quote is contained in the actual data to be inserted, the command often becomes corrupted. To solve the problem, simply replace any single quote with two quotes (not the double quote character but two single-quote characters).
declare #var varchar(100)
select #var = 'txt'
select char(39)+#var+char(39) -- with single quote
select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES
(''' + CAST(Endereco_Id as varchar) + ''','
+ ....
You have to use ' in string two times:
declare #var varchar(100)
select #var = 'txt'
select ' '+#var+' ' -- without single quote
select ''''+#var+'''' -- with single quote
Related
I am trying to write a query in CSV format, it is below:
SELECT SUBSTRING
(
(
SELECT ',' + [symbol], + ',' + [date] + ',' + [price]
FROM csvFormatTable
FOR XML PATH('')
)
,2,200000
)
AS CSV
and it mostly gives the correct result apart from the ',' at the end of the line but I do want to replace it with a line break. I've seen CHAR(10) and similar stuff like that but it does not give a line break but instead a '#x0D'. The result of the query above is what I have (without the char(10) stuff) below:
symbol,date,price,mikeCode,2019-04-10,50,mikeCode,2019-04-11,200,mikeCode,2019-04-12,10,
Where as it should be:
symbol,date,price
mikeCode,2019-04-10,50
mikeCode,2019-04-11,200
mikeCode,2019-04-12,10
It needs the line break so it can be readable as a CSV.
Assuming you're on SQL Server 2016- then use (N)CHAR(13) and (N)CHAR(10). You'll then need to use TYPE, to avoid the escaping of the characters, and then value to get the values out.
SELECT STUFF((SELECT ',' + CHAR(13) + CHAR(10) + [symbol] +
',' + [date] + ',' + [price]
FROM csvFormatTable
FOR XML PATH(''),TYPE).value('.','varchar(MAX)'),1,3,'') AS CSV;
If you are on SQL Server 2017+, you can use STRING_AGG
SELECT STRING_AGG(CHAR(13) + CHAR(10) + ',' + [symbol] + ',' + [date] + ',' + [price],CHAR(13) + CHAR(10))
FROM csvFormatTable --Untested
db<>fiddle
Thanks to #Larnu I changed the settings in my SMSS (link on how to do this is here):
How to correctly insert newline in nvarchar
And I just changed my query around a bit to get the wanted results to
DECLARE #SQL NVARCHAR(MAX)
SET #SQL =
'
DECLARE #test NVARCHAR(MAX)
SET #test = (SELECT STRING_AGG(CHAR(10) + [symbol] + '','' + [date] + '','' + [price], CHAR(13) ) FROM csvFormatTable)
SELECT #test
'
EXEC(#SQL)
I have a query of the form
SELECT '(''' +
SomeVarCharColumn +
''',' +
CONVERT(NVARCHAR(MAX), SomeIntColumn) +
',' +
CONVERT(NVARCHAR(MAX), SomeOtherIntColumn)
+ ')'
FROM SomeTable
and all the results are NULL. Any idea where I'm going wrong?
null + 1 is null
null + 'things' is null
try this instead:
select '('''
+ isnull(somevarcharcolumn,'')
+ ''','
+ isnull(convert(nvarchar(max), someintcolumn),'null')
+ ','
+ isnull(convert(nvarchar(max), someotherintcolumn),'null')
+ ')'
from sometable
If any column is NULL, then the value is NULL. Use COALESCE():
SELECT '(''' + COALESCE(SomeVarCharColumn, '') + ''',' +
COALESCE(CONVERT(NVARCHAR(MAX), SomeIntColumn), '') + ',' +
COALESCE(CONVERT(NVARCHAR(MAX), SomeOtherIntColumn), '') + ')'
FROM SomeTable
Use the CONCAT() function. When null values are encountered they are simply omitted from the resulting string. Additionally, int to char conversions are implicit no need for the convert, you can find a chart of implicit conversions here https://msdn.microsoft.com/en-us/library/ms187928.aspx
SELECT
CONCAT('(''',SomeVarCharColumn,''',',SomeIntColumn,',',SomeOtherIntColumn,')') AS NewVarchar
FROM SomeTable
Please se my code below
set #query = 'SELECT tenantcode, locationd, name, MONTH,' +
'Year1 as' + '[' + #Year1 + ']' +
',Year2 as' + '[' + #Year2 + ']' +
',Year3 as' + '[' + #Year3 + ']' +
',Year4 as' + '[' + #Year4 + ']' +
',Year5 as' + '[' + #Year5 + ']' +
'from #SalesPerYear' +
'UNION ALL' +
'SELECT tenantcode, locationd, name, total , t1, t2,t3,t4,t5 FROM #TotalSales '
EXECUTE (#query)
That is part of my codes in the desire in achieving a final output in SQL WHERE COLUMN NAMES should be dynamic (in this case, the changing YEAR NAME such as 2011, 2012,2013 etc)
When execute my stored procedure, there is an error like this
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'tenantcode'.
When I remove the Union all, both queries worked individually. What could be the problem here.
You're missing a space between from #SalesPerYear and UNION ALL and also the following SELECT.
....
'from #SalesPerYear '
^---here
'UNION ALL' +
' SELECT tenantcode, locationd, name, total , t1, t2,t3,t4,t5 FROM #TotalSales '
^--- and here
Thats the easiest way to demonstrate it, you can of course just put a space either side of UNION ALL
' UNION ALL ' +
Using SQL Server 2008
DECLARE #myVariable nvarchar (500)
SET #myVariable = 'select distinct b.*,v.vertrag_id,v.VersicherungsscheinNummer
from CRM_Wifo_GmbH.dbo.vertrag_168 v,temp_universa b
where v.VersicherungsscheinNummer like '%' + b.vsnr + '%
and v.gesellschaft_id in('59','66')'
I have to set the value of this type in a variable. How could I do this? Is it possible? USING ' ' sign in a string?
You just need to escape the single quote ' using 2 single quotes instead ''
DECLARE #myVariable nvarchar (500)
SET #myVariable =
N'select distinct b.*,v.vertrag_id,v.VersicherungsscheinNummer
from CRM_Wifo_GmbH.dbo.vertrag_168 v,temp_universa b
where v.VersicherungsscheinNummer like ''%'' + b.vsnr + ''%
and v.gesellschaft_id in(''59'',''66'')'
I am also using N', so that I can span the string on multiple lines
Alternative solutions :
DECLARE #myVariable nvarchar (500)
SET #myVariable = 'select distinct b.*,v.vertrag_id,v.VersicherungsscheinNummer from CRM_Wifo_GmbH.dbo.vertrag_168 v,temp_universa b where v.VersicherungsscheinNummer like ' + char(39) + '%' + char(39) + ' + b.vsnr + ' + char(39) + '% and v.gesellschaft_id in(' + char(39) + '59' + char(39) + ',' + char(39) + '66' + char(39) + ')'
But i suggesst you, using 2 single quotes.
I asked a question a couple days ago about creating INSERTs by running a SELECT to move data to another server. That worked great until I ran into a table that has full on HTML and apostrophes in it. What's the best way to deal with this? Lucking there aren't too many rows so it is feasible as a last resort to 'copy and paste'. But, eventually I will need to do this and the table by that time will probably be way too big to copy and paste these HTML fields.
This is what I have now:
select 'Insert into userwidget ([Type],[UserName],[Title],[Description],[Data],[HtmlOutput],[DisplayOrder],[RealTime],[SubDisplayOrder]) VALUES ('
+ ISNULL('N'''+Convert(varchar(8000),Type)+'''','NULL') + ','
+ ISNULL('N'''+Convert(varchar(8000),Username)+'''','NULL') + ','
+ ISNULL('N'''+Convert(varchar(8000),Title)+'''','NULL') + ','
+ ISNULL('N'''+Convert(varchar(8000),Description)+'''','NULL') + ','
+ ISNULL('N'''+Convert(varchar(8000),Data)+'''','NULL') + ','
+ ISNULL('N'''+Convert(varchar(8000),HTMLOutput)+'''','NULL') + ','
+ ISNULL('N'''+Convert(varchar(8000),DisplayOrder)+'''','NULL') + ','
+ ISNULL('N'''+Convert(varchar(8000),RealTime)+'''','NULL') + ','
+ ISNULL('N'''+Convert(varchar(8000),SubDisplayOrder)+'''','NULL') + ')'
from userwidget
Which is works fine except those pesky apostrophes in the HTMLOutput field. Can I escape them by having the query double up on the apostrophes or is there a way of encoding the field result so it won't matter?
You can replace the single apostrophe with double apostrophes.
ISNULL('N'''+ REPLACE(Convert(varchar(8000),Type), '''', '''''') + '''','NULL') + ','
You should use parameters instead of injecting values into your SQL query.
Use QUOTENAME function
declare #valueAsNull as varchar(10)
set #valueAsNull = quotename('NULL','''')
SELECT 'Insert into userwidget ([Type],[UserName],[Title],[Description],[Data],[HtmlOutput],[DisplayOrder],[RealTime],[SubDisplayOrder]) VALUES (' +
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(Type,'NULL'),''''), #valueAsNull,'NULL') + ', '
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(Username,'NULL'),''''), #valueAsNull,'NULL') + ', '
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(Title,'NULL'),''''), #valueAsNull,'NULL') + ', '
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(Description,'NULL'),''''), #valueAsNull,'NULL') + ', '
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(Data,'NULL'),''''), #valueAsNull,'NULL') + ', '
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(HTMLOutput,'NULL'),''''), #valueAsNull,'NULL') + ', '
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(DisplayOrder,'NULL'),''''), #valueAsNull,'NULL') + ', '
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(RealTime,'NULL'),''''), #valueAsNull,'NULL') + ', '
REPLACE(QUOTENAME(Convert(varchar(8000),ISNULL(SubDisplayOrder,'NULL'),''''), #valueAsNull,'NULL') + ')'
FROM userwidget