Using CAST() and resulting an error - sql

I'm trying to do a SELECT for concatenating 2 columns in MSSQL 2008R2.
COALESCE(SeriePolita, '') + COALESCE(CAST(NumarPolita AS numeric), '') as NrSeriePolita
Both SeriePolita and NumarPolita are NVARCHAR. The difference between them is that SeriePolita contains text and NumarPolita only number.
I need to convert NumarPolita from 0008838630 to 8838630.
As you ca see in the code line, i used CAST() for NumarPolita but i get this message:
Conversion failed when converting the nvarchar value 'AAA' to data type int.
Is there another way to covert a NVARCHAR to INT/NUMERIC?
Thank you!

You need to cast it back to NVARCHAR to concatenate it, since concatenation of nvarchar with numeric is not possible:
COALESCE(SeriePolita, '') + COALESCE(CAST(CAST(NumarPolita AS numeric) AS NVARCHAR), '') as NrSeriePolita

You can use a CASE expression and ISNUMERIC:
SELECT
CASE
WHEN ISNUMERIC(NumarPolita)
THEN COALESCE(SeriePolita, '') + COALESCE(CAST(NumarPolita AS numeric), '')
ELSE ''
END AS NrSeriePolita
FROM ...
Alternatively, if you only need the records where this conversion is possible, you can use ISNUMERIC in the WHERE clause.

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'

Looping a CASE WHEN and REPLACE statement in SQL

Apologies for the multiple basic questions - I am very new to SQL and still trying to work things out.
I would like to insert records from my staging table to another table in my database, both removing the double quotes in the source file with a 'replace' function and converting the data from nvarchar (staging table) to datetime2. I can't quite work out how to do this: if I loop the 'case when' within 'replace', as below, then SQL doesn't recognise my data and nulls it out:
CASE WHEN ISDATE (REPLACE([Column1], '"', '')) = 1
THEN CONVERT(datetime2, Column1, 103)
ELSE null END
However if I loop my 'replace' within my 'case when', as below, SQL gives me an error message saying that it is unable to convert nvarchar into datetime2:
LTRIM(REPLACE([Column1], '"', '')
,CASE WHEN ISDATE(Column1) = 1 THEN CONVERT(datetime2, Column1, 103)
ELSE null END
What order / syntax do I need to be using to achieve this? An example of the data field would be:
"16/10/2017"
It uploads to my staging table as nvarchar
"16/10/2017"
and I would like to move it into my table2 as datetime2:
16/10/2017
Instead of isdate(), use try_convert():
TRY_CONVERT(datetime2, LTRIM(REPLACE([Column1], '"', ''), 103)
I think your confusion is that you need to do the string manipulation before the conversion. To do this, the string manipulation needs to be an argument to the conversion.
You are doing it right. The problem is, convert needs value without " ", and hence your convert was failing.
Just try this :
select
CASE WHEN ISDATE (REPLACE([Column1], '"', '')) = 1
THEN CONVERT(datetime2, (REPLACE([Column1], '"', '')), 103)
ELSE null END
from #tbl
more details : cast and convert doc

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)