SQL Server SELECT To Return String Including Single Quotes - sql

I need to get a formatted string with data from a SELECT statement. The problem is that I need it to return with single quotes. Here's an example.
I have a table that contains 2 columns TrainingSwipeID (int) and ExtendedDate (datetime). For an example I have a row in the table that contains
TrainingSwipeID = 123
TrainingEnd = 04/23/2019 09:00:00
I need to create a SELECT statement that will return the formatted string such as
{'TrainingSwipeID':123,'TrainingEnd ':04/23/2019 09:00:00}
I've researched and found that you can double single quote to get around this issue. I've tried the following with no luck and I get the following error "Conversion failed when converting the varchar value '{'TrainingSwipeID':' to data type int."
SELECT '{''TrainingSwipeID'':' + TrainingSwipeID + '''TrainingEnd'':' + TrainingEnd + '}'
AS MyFormattedString
FROM TrainingSwipe
Can anyone help?

The numeric and date/time data types have a higher precedence than the string data types. That's why you need to convert the numeric types into strings and prevent undesired implicit conversions.
SELECT '{''TrainingSwipeID'':' + CAST(TrainingSwipeID AS varchar(15))
+ '''TrainingEnd'':' + CONVERT( varchar(20), TrainingEnd , 101) + ' '
+ CONVERT( varchar(20), TrainingEnd , 8) + '}'
AS MyFormattedString
FROM TrainingSwipe

I finally used the simplest answer from #AlexKudryashev but Luis' answer worked as well.
SELECT CONCAT('{''TrainingSwipeID'':' , TrainingSwipeID, ',''TrainingEnd'':', TrainingEnd, '}')

Related

SQL Server concat empty string (not null)

I am trying to concat the columns here but when I encounter a column with empty / blank string, the concat failed.
I need to do some formatting for each column with different data type, so I am not using the CONCAT function. Using the conventional way like
SELECT CONVERT(varchar, [Priority]) + '~' + CONVERT(varchar,[AP_type]) + '~' + [AP_Name] + '~'
FROM table
Any suggestions on how I can concat empty string ?
Results I am looking :
0~0~~~~In~In
Thanks.
Couple of things.
always best to specify the length when converting to varchar. For example varchar(50)
concat() will handle nulls as empty string and there is no need to convert. Oddly enough, char(0) creates the odd behavior.
Example
Declare #YourTable Table ([priority] varchar(50),[ap_type] varchar(50),[ap_name] varchar(50),[ap_par] varchar(50),[infoText] varchar(50),[TxtCame] varchar(50),[TxtWent] varchar(50))
Insert Into #YourTable Values
(0,0,'','','','In','In')
,(0,0,'','',null,'In','In') -- Has Null
,(0,0,'','',char(0),'In','In') -- Has Char(0) ... Truncates without NullIf()
Select NewString = concat(priority,'~',ap_type,'~',ap_name,'~',ap_par,'~',NullIf(infoText,char(0)),'~',TxtCame,'~',TxtWent)
from #YourTable
Returns
NewString
0~0~~~~In~In
0~0~~~~In~In
0~0~~~~In~In -- NullIf() was required to fix

Concatenate and add a character to integer columns in SQL

I have a 10 Character length values in a column in SQL Server. I need to split that column at fixed length and remove the leading zeros and add a - after each of the values.
I am able to split the values by using Substring and converting them to int. It is working well.
However, when I try to concatenate it is failing. Appreciate if you can help.
SELECT TOP 1 R.COL1, CAST(SUBSTRING(R.COL1,1,1) AS int) AS F1,CAST(SUBSTRING(R.COL1,2,5) AS int) AS F2,CAST(SUBSTRING(R.COL1,7,4) AS int) AS F3 CAST(SUBSTRING(R.COL1,1,1) AS int) +'-' +CAST(SUBSTRING(R.COL1,2,5) AS int) +'-' + CAST(SUBSTRING(R.COL1,7,4) AS int) AS finalString FROM MYTABLE R
If the value for COL1 IS 1012950001 the finalString I am expecting is 1-1295-1
however the result I am getting from the above query is 1297 as it is adding all the values.
Appreciate if you can help.
You can't use the + operator with a numerical data type and a varchar that cannot implicitly be converted to that data type. Something like 1 + 'a' isn't going to work, as 'a' isn't an int, and can't be implicitly converted to one.
If you are mixing data types, then use CONCAT, which implicitly converts each part into a (n)varchar:
CONCAT({Numerical Expression},'a',{Other varchar Expression})
You can use concat method to concatenate the substring value
select
concat(CAST(SUBSTRING('1012950001',1,1) AS int), '-',
CAST(SUBSTRING('1012950001',2,5) AS int), '-',
CAST(SUBSTRING('1012950001',7,4) AS int)) AS finalString
This will give you the expected result '1-1295-1'

"Error converting data type nvarchar to float" with CASE WHEN Statement

I'm trying to run a query with the following as one of the select statements, and I keep getting the error "Error converting data type nvarchar to float." I've been converting VBA IIf statements to CASES and I can't seem to get the conversions right. fld2 is nvarchar(15) and fld1 is a float data type. I need help pinpointing why this error is being thrown.
CASE WHEN (IsNumeric([fld2]) = 1) THEN Round(Convert(nvarchar,[fld2]) +
' / ' + Convert(nvarchar,[fld1]),(Len(Convert(nvarchar,[theData])) -
Charindex(Convert(nvarchar, [fld2]),'.'))) ELSE [fld2] END,
As is, your example would produce quite a funny expression for SQL server to evaluate. Let's substitute values for fld1, fld2, and theData as an example to see what you're trying to do:
[fld1] = 42.0
[fld2] = N'69.56'
[theData] = N'something'
(an N before a string makes it an nvarchar instead of varchar)
With substitutions, the resulting query would look like this:
CASE WHEN (IsNumeric(N'69.56') = 1) THEN
Round(Convert(nvarchar,'69.56') + ' / ' + Convert(nvarchar, 42.0),
(Len(Convert(nvarchar,'something')) - Charindex(Convert(nvarchar, N'69.56'),'.')))
ELSE
N'69.56'
END
Since you don't need to convert an nvarchar to nvarchar explicitly, your query actually looks more like:
CASE WHEN (IsNumeric(N'69.56') = 1) THEN
Round(N'69.56 / ' + Convert(nvarchar, 42.0),
(Len(N'something') - Charindex(N'69.56','.')))
ELSE
N'69.56'
END
So there are a couple of problems:
You're passing a varchar value into the ROUND() function, which expects a numeric value, not an expression
The two paths of the CASE statement are returning different types
What I think your query should look like is:
CASE WHEN IsNumeric([fld2]) = 1 THEN
CONVERT(nvarchar, ROUND(CONVERT(float, [fld2]) / [fld1],
(LEN([theData]) - CHARINDEX([fld2], '.'))))
ELSE
[fld2]
END
The above does the math and rounding on numeric results instead of strings, doesn't do any unnecessary conversions, and also returns the same type in both cases.

Varchar to Numeric conversion - CLR or 'e0'

I want to convert data from Varchar column to Numeric data type -
so before conversion I am calling ISNUMERIC function to check whether data is numeric and if yes convert it to numeric data type. But I am facing an issue -
IsNumeric function is not behaving as expected -
- IsNumeric(x) returns true - when varchar value has both comma and a tab character (Char(9)),
- IsNumeric(x) returns false - when varchar value has only tab character and no comma
It is explained with the help of below SQL -
DECLARE #propValue AS VARCHAR(50)
SET #propValue = '1,592 ' -- contains comma + tab (Char(9))
SELECT ISNUMERIC(#propValue) -- Returns 1
--If ISNUMERIC func returns true for this value, lets convert this Varchar value to Numeric
SELECT CAST(#propValue AS Numeric(19, 4)) -- :-( Error converting data type varchar to numeric.
I Googled and found various solutions to tackle this problem -
--Solution 1: use 'e0'
SELECT ISNUMERIC(#propValue + 'e0') -- Returns 0
--Solution 2: remove comma before calling IsNumeric()
SELECT ISNUMERIC(REPLACE(#propValue, ',', '')) -- Returns 0
--Solution 3
--Call CLR function to parse Varchar value
What is the recommended solution in above scenario and why?
Also, I would really appreciate if anyone can explain why IsNumeric(x) returns false - when varchar value has only tab character and no comma?
Thank you!
Keep in mind that ISNUMERIC() = 1 does not mean "can be converted to every numeric type" but rather "can be converted to at least one numeric type." This comes up a lot where the value can be converted to at least one numeric type, but not the one you want. A much more basic example:
IF ISNUMERIC(256) = 1
SELECT CONVERT(TINYINT, 256);
If you have strings that have known violations (such as tabs), then why not also replace tabs? Why not prevent garbage data from getting into this value in the first place?
This works but it is quite ugly:
DECLARE #x TABLE (propValue VARCHAR(50));
INSERT #x SELECT '1,592' + CHAR(9)
UNION ALL SELECT '55' + CHAR(9) + '32'
UNION ALL SELECT CHAR(9) + '7,452.32 '
UNION ALL SELECT 'foo'
UNION ALL SELECT '74';
SELECT CONVERT(NUMERIC(19,4),
LTRIM(RTRIM(REPLACE(REPLACE(propValue, CHAR(9), ''), ',', '')))
)
FROM #x
WHERE ISNUMERIC(LTRIM(RTRIM(REPLACE(REPLACE(propValue,
CHAR(9), ''), ',', ''))) + 'e0') = 1;
While not applicable to your exact question, I wrote a FAQ about this 10 years ago: http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html
ISNUMERIC(RTRIM(LTRIM(x))) = 1

How to convert Varchar to Int in sql server 2008?

How to convert Varchar to Int in sql server 2008.
i have following code when i tried to run it wont allowed me to convert Varchar to Int.
Select Cast([Column1] as INT)
Column1 is of Varchar(21) NOT NULL type and i wanted to convert it into Int.
actually i am trying to insert Column1 into another table having Field as INT.
can someone please help me to convert this ?
Spaces will not be a problem for cast, however characters like TAB, CR or LF will appear as spaces, will not be trimmed by LTRIM or RTRIM, and will be a problem.
For example try the following:
declare #v1 varchar(21) = '66',
#v2 varchar(21) = ' 66 ',
#v3 varchar(21) = '66' + char(13) + char(10),
#v4 varchar(21) = char(9) + '66'
select cast(#v1 as int) -- ok
select cast(#v2 as int) -- ok
select cast(#v3 as int) -- error
select cast(#v4 as int) -- error
Check your input for these characters and if you find them, use REPLACE to clean up your data.
Per your comment, you can use REPLACE as part of your cast:
select cast(replace(replace(#v3, char(13), ''), char(10), '') as int)
If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR and LF before it is entered.
you can use convert function :
Select convert(int,[Column1])
That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123 to an int.
UPDATE
Based on your comments I would remove any spaces that are in the values you are trying to convert.
That is the correct way to convert it to an INT as long as you don't have any alpha characters or NULL values.
If you have any NULL values, use
ISNULL(column1, 0)
Try the following code. In most case, it is caused by the comma issue.
cast(replace([FIELD NAME],',','') as float)
Try with below command, and it will ask all values to INT
select case when isnumeric(YourColumn + '.0e0') = 1
then cast(YourColumn as int)
else NULL
end /* case */
from YourTable
There are two type of convert method in SQL.
CAST and CONVERT have similar functionality. CONVERT is specific to SQL Server, and allows for a greater breadth of flexibility when converting between date and time values, fractional numbers, and monetary signifiers. CAST is the more ANSI-standard of the two functions.
Using Convert
Select convert(int,[Column1])
Using Cast
Select cast([Column1] as int)