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
Related
Want to set Collation in Select statement in SQL.
I have below SQL query for which I get error :
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AI" in the equal to operation.
I have idea for setting collation for joins, in this case I dont have idea.
Below is the SQL Query for which I am trying to set COLLATE SQL_Latin1_General_CP1_CI_AI,
SET #ColumnNames_CSV_Responses_Smoker_Retail = ' ';
SELECT #ColumnNames_CSV_Responses_Smoker_Retail = COALESCE(#ColumnNames_CSV_Responses_Smoker_Retail, '') +
CASE WHEN QuestionType IN (2, 3, 4)
AND EXISTS (SELECT *
FROM Optiontable
WHERE Option_Code = '1001'
AND Optiontable.Question_ID = Question.QuestionID) THEN 'dbo.ReplaceBrandIDWithCode(''' + CAST(QuestionID AS varchar) + ''',[' + CAST(QuestionID AS varchar) + ']) AS [' + CAST(QuestionID AS varchar) + '],'
WHEN QuestionType IN (3) THEN 'REPLACE(RTRIM(LTRIM([' + CAST(QuestionID AS varchar) + '])),'' '', ''#'') AS [' + CAST(QuestionID AS varchar) + '],'
WHEN QuestionType IN (4) THEN 'REPLACE(REPLACE(SUBSTRING(RTRIM(LTRIM([' + CAST(QuestionID AS varchar) + '])),1, LEN(RTRIM(LTRIM([' + CAST(QuestionID AS varchar) + ']))) - 1),''^'', ''#''),'','','''') AS [' + CAST(QuestionID AS varchar) + '],'
ELSE 'REPLACE(RTRIM(LTRIM([' + CAST(QuestionID AS varchar) + '])),'','', '' '') AS [' + CAST(QuestionID AS varchar) + '],'
END
FROM Question
WHERE CAST(QuestionID AS varchar)IN (SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #Table_Name)
ORDER BY QuestionSeqNumber;
Any Help will be Appreciated, Thanks.
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 select statement that is combining multiple segments of a persons name. This isn't anything new.
SELECT FirstName + ' ' + LastName AS FullName FROM MyTable
I then tried to add the middle initial to this and I came up with the following
SELECT FirstName + ' ' + ISNULL(MiddingInitial + ' ', '') + LastName AS FullName FROM MyTable
This appears to work, but during my testing of ISNULL(), I came across an odd behavior. I'm aware that NULL + 'any string' resolves to NULL. However this was just plain odd...
Here's my code, and what I get out as a result...
print '''' + isnull(null + 'Any String','Results in null') + ''''
print '''' + isnull(null + 'Any','Results in null') + ''''
print '''' + isnull(null + 'A','Results in null') + ''''
print '''' + isnull(null + '','Results in null') + ''''
/*
'Results in '
'Resu'
'Re'
'Re'
*/
Any idea of why this behavior occurs? Does it do the same for you?
It comes down to the datatypes you're working with and the behavior of the ISNULL function. Let's look at one example:
null + 'Any String'
The above fits perfectly into a varchar(11) datatype. The NULL (which is really just the result of char(0) and has length 1) and a regular 10-character string concatenated together makes for 11 characters total. The replacement string -- the second parameter to your ISNULL function -- is going to be forced to fit into a varchar(11), so it is truncated to 11 characters.
The pattern repeats for the remaining items, with a special case for the empty string.
If you don't want this to happen, use COALESCE, which instead of taking the datatype of the first item in the list, it uses data type precedence. A varchar(15) takes precedence over a varchar(11), so you will get the full replacement string:
print '''' + coalesce(null + 'Any String','Results in null') + ''''
print '''' + coalesce(null + 'Any','Results in null') + ''''
print '''' + coalesce(null + 'A','Results in null') + ''''
print '''' + coalesce(null + '','Results in null') + ''''
/*
'Results in null'
'Results in null'
'Results in null'
'Results in null'
*/
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.
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