SQL Server concat empty string (not null) - sql

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

Related

Remove characters before '-' and after '-' keeping the middle of the string that contain more one character '-'

I got the following entry in my database (varchar data type):
5-359-258756-54
2-456-58994-85
4-458 -478698-42
5-876-5878-26
I want to exclude first number plus char '-', last two numbers plus previous '-' and remove the spaces when available in the middle char ' -'.
The final result must be:
359-258756
456-58994
458-478698
876-5878
I tried to use mainly charindex & patindex with replace ' ','' based in forum suggestions, but not show the expected result, the most close that I could return was 458-478698-42 (removing the first number plus character and the space),
How can I solve it?
If you string format is consistent, then you an use parsename()
Example
Declare #YourTable table (SomeCol varchar(50))
Insert Into #YourTable values
('5-359-258756-54')
,('2-456-58994-85')
,('4-458 -478698-42')
,('5-876-5878-26')
Select *
,NewVal = replace(parsename(replace(SomeCol,'-','.'),3)
+'-'
+parsename(replace(SomeCol,'-','.'),2)
,' ','')
From #YourTable
Results
SomeCol NewVal
5-359-258756-54 359-258756
2-456-58994-85 456-58994
4-458 -478698-42 458-478698
5-876-5878-26 876-5878

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'

Convert VarChar to Float with different culture format

From different external sources I get data where some numbers are in a NVarChar field. Until now I used a REPLACE with a CAST to ensure that numbers with a "," where cast the right way. Like this:
select cast(replace('12,5',',','.') as float)
select cast(replace('12.5',',','.') as float)
This has worked just fine, but now I get data where there is also a thousand separator in. Like this:
select cast(replace('2.012,5',',','.') as float)
select cast(replace('2,012.5',',','.') as float)
It' broken.
Is there a way to detect which data format is used in a NVarChar with a number?
I have tried to use TRY_PARSE with a culture parameter, it works well if there is a thousand separator but not without:
SELECT #Fuelunits =
CASE
WHEN ISNUMERIC(TRY_PARSE(#Hoeveelheid AS decimal(9,2) USING 'nl-NL')) = 1
THEN CAST(TRY_PARSE(#Hoeveelheid AS decimal(9,2) USING 'nl-NL') AS FLOAT)
ELSE CAST(TRY_PARSE(#Hoeveelheid AS decimal(9,2) USING 'en-US') AS FLOAT)
END
The problem is that I have to use this in an UPDATE and that that the data format can differ in the same table.
Any suggestions?
You can use CHARINDEX() to work out what separators are present and where they are in the string along with a CASE expression to handle different cases before you REPLACE and CAST to FLOAT:
CREATE TABLE #vals (val NVARCHAR(10));
INSERT INTO #vals
(
val
)
VALUES
(N'2.012,5'),
(N'2,012.5');
SELECT CAST(CASE
-- is there a '.' in a position before a ','?
WHEN CHARINDEX('.', val) < CHARINDEX(',', val) THEN
-- yes - remove the '.' and replace the ',' with '.'
REPLACE(REPLACE(val, '.', ''), ',', '.')
ELSE
-- no - just remove the ','
REPLACE(v.val, ',', '')
END AS FLOAT)
FROM #vals AS v;
DROP TABLE #vals;
References:
CHARINDEX (Transact-SQL)
Searches an expression for another expression and returns its starting position if found.

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)

T-SQL String Functions: difference between using Left/Right and Substring and strange behaviour

I am using SQL Server 2008 & 2005 (Express). I'm trying to extract part of an alpha numeric string from a varchar field.
RIGHT(str_field, 3) yields null values but SUBSTRING(str_field, LEN(str_field)-2, LEN(str_field)) gives the right value. LEFT(str_field, 7) gives the expected values. What gives?
I would have thought that RIGHT(str_field, 3) and SUBSTRING(str_field, LEN(str_field)-2, LEN(str_field)) are equivalent expressions.
You have trailing spaces
RIGHT will yield spaces but LEN ignores trailing spaces
DECLARE #foo varchar(100)
SET #foo = 'abc12345def ' --3 spaces
--right or substring
SELECT RIGHT(#foo, 3)
SELECT SUBSTRING(#foo, LEN(#foo)-2, LEN(#foo))
--demonstrate you get spaces
SELECT REPLACE(RIGHT(#foo, 3), ' ', 'z') --single space
--length differences
SELECT LEN(#foo), DATALENGTH(#foo)
--solution
SELECT RIGHT(RTRIM(#foo), 3)
--or trim your column values before storing
See SET ANSI_PADDING
Note: you won't get NULL for non NULL input...
--only NULL if you send in NULL
SELECT RIGHT(NULL, 3)