concat two columns in sql - sql

I have four columns on data gridview and want them to concat in sql and exporting it to txt file but everytime i export this is my result.
My result
0010000 01500 00000 0001600
output required
001000001500000000001600
SQL Query:
string stringSql = " SELECT distinct " +
"REPLACE(RIGHT('00'+CAST(CAST(bat.PCN_Charge* 100.00 AS INT) AS VARCHAR(5)),8) as CLAIMAMT, + RIGHT('0'+CAST(CAST([CFee] * 100 AS INT) AS VARCHAR(5)),5),' ','' )as CFEE," +
"REPLACE(RIGHT('00000'+CAST(CAST([Solictors Fees] AS INT) AS VARCHAR(5)),5), + RIGHT('000'+CAST(CAST(bat.PCN_Charge + [CFee]*100 AS INT) AS VARCHAR(5)),9),' ','') as TotalAMT " +

Judging from the manual:
Method 1: Concatenating two strings
SELECT 'FirstName' + ' ' + 'LastName' AS FullName
Method 2: Concatenating two Numbers
SELECT CAST(1 AS VARCHAR(10)) + ' ' + CAST(2 AS VARCHAR(10))
Method 3: Concatenating values of table columns
SELECT FirstName + ' ' + LastName
FROM AdventureWorks.Person.Contact
In your case, you should do the same, avoiding the space in between.

select first_column+' '+second_c+' '+third_c+' '+forth_c
from table_name

try it
declare #result varchar(500)
set #result = ''
select #result = #result +' '+first_c+' '+second_c+' '+third_c+' '+forth_c
from table_name

declare #a varchar(50)
set #a='0010000 01500 00000 0001600'
select replace(#a,' ','')
SEE DEMO

Related

Invalid length parameter passed to the LEFT or SUBSTRING function in my query. It runs perfect id DTS 2008 but gives this error in SSIS 2014

DECLARE #ColumnTotal INT,
#HTProcOfficeColumnNames NVARCHAR(4000),
#TBLColumnNames NVARCHAR(4000),
#query NVARCHAR(4000),
#subqueryInsert NVARCHAR(4000),
#subqueryValues NVARCHAR(4000)
SELECT #ColumnTotal = Count(*)
FROM (SELECT htprocoffice
FROM table
WHERE COLUMN NOT LIKE '% - CO'
GROUP BY COLUMN) T
SELECT #HTProcOfficeColumnNames = COALESCE(#HTProcOfficeColumnNames
+ ',[' + htprocoffice + ']', '[' + htprocoffice + ']')
FROM (SELECT htprocoffice
FROM table
WHERE COLUMN NOT LIKE '% - CO'
GROUP BY COLUMN) T
ORDER BY COLUMN
SELECT #TBLColumnNames = COALESCE(#TBLColumnNames + ',' + NAME, NAME)
FROM table
WHERE id IN (SELECT id
FROM table
WHERE type = 'U'
AND NAME = 'TableName')
AND NAME LIKE 'HTOffice%'
ORDER BY NAME
Is there any error in the below code?
set #subqueryInsert = substring(#TBLColumnNames,1,#ColumnTotal*11-1) --The error occurs here but not sure though.
set #subqueryInsert = 'INSERT INTO Table
(RunDate,OrderBy,Period,IConOffice,IConOfficeType,'+ #subqueryInsert+')'
set #subqueryValues =
replace(replace(#HTProcOfficeColumnNames,'[',''''), ']','''')

Why does SQL Server conversion to bigint cause an error?

I am trying to convert varchar to bigint:
select convert(bigint, (select(Replace((select value from sometable), ' ', ''))))
Why is it giving error???
Error converting data type varchar to bigint.
thanks in advance
Update
This is part of query I am trying:
select top 1 *
into #tblTemp
from testTable
where Status = 0
order by Sno
declare #mobile varchar(50)
set #mobile = (select(Replace((select mobile from #tblTemp), ' ', '')))
--set #mobile = (select( Replace(' 9428017524', ' ', '')))
select convert(bigint, #mobile)
drop table #tblTemp
Try this
select convert(bigint, CASE WHEN ISNUMERIC(#mobile + 'e0') = 0
THEN 0 ELSE #mobile)
-- add this case statement to return only numeric values,
-- your query will fail for values like '123-415-6789', '(123)415-6789'
Check your mobile numbers data and see if there are any unexpected values in that column, you may have to replace '-' or '(' or ')' etc with ''.
SeLECT * FROM #tblTmp
WHERE ISNUMERIC(Replace(mobile, ' ', '') + 'e0') = 0;
I am not sure what your real string is but for safety you can check ISNUMERIC() before convertion.
DECLARE #mobile varchar(50)
SELECT #mobile = REPLACE(mobile, ' ','') --much simplified version
FROM #tblTemp
IF ISNUMERIC(#mobile)
SELECT CONVERT(bigint, #mobile)
ELSE
SELECT 0
Just by reading your queries, you don't need a temp table here at all. Everything can be done in a single query
SELECT TOP (1) CONVERT(bigint, CASE ISNUMERIC( REPLACE(mobile,' ','') )
WHEN 1 THEN REPLACE(mobile,' ','')
ELSE 0 END )
FROM testTable
WHERE Status = 0
ORDER By Sno

sybase ISNULL - are the conditions too long?

I am trying to unmangle a very old variable. It was a full name entered all in one field and is found in two separate tables. In most newer places the name is in three logical columns, first, middle, last. In these it is all together and I am trying to strip it out to first initial, last name. I found the following here and modified it:
http://dbaspot.com/sqlserver-programming/365656-find-last-word-string.html
DECLARE #full_name VARCHAR(20)
DECLARE #fullname VARCHAR(20)
SELECT #full_name = REVERSE('John A Test')
SELECT #fullname = REVERSE('Joe Q Public')
SELECT #final = ISNULL(
(right(#full_name,1) + '. ' + (REVERSE(SUBSTRING(#full_name, 1,
CHARINDEX(' ',#full_name) - 1)))),
(right(#fullname,1) + '. ' + (REVERSE(SUBSTRING(#fullname, 1,
CHARINDEX(' ',#fullname) - 1 ))))
)
When I leave full_name there it works fine...returns J. Test. When I null it the default should be
J. Public but instead ends up as .. When I test each line separately they work. I tried COALESCE as well with the same results. Is this too many brackets for ISNULL or ????
You have problem with right(#full_name,1) + '. ', for example:
select null+'.'
gives you ..
Try to change your code using case as below:
DECLARE #full_name VARCHAR(20)
DECLARE #fullname VARCHAR(20)
DECLARE #final VARCHAR(20)
SELECT #full_name = null--REVERSE('John A Test')
SELECT #fullname = REVERSE('Joe Q Public')
SELECT #final = case
when #full_name is not null
then (right(#full_name,1) + '. ' + (REVERSE(SUBSTRING(#full_name, 1,
CHARINDEX(' ',#full_name) - 1))))
else (right(#fullname,1) + '. ' + (REVERSE(SUBSTRING(#fullname, 1,
CHARINDEX(' ',#fullname) - 1 ))))
end
select #final

How to get rid of double quote from column's value?

Here is the table, each column value is wrapped with double quotes (").
Name Number Address Phone1 Fax Value Status
"Test" "10000000" "AB" "5555" "555" "555" "Active"
How to remove double quote from each column? I tried this for each column:-
UPDATE Table
SET Name = substring(Name,1,len(Name)-1)
where substring(Name,len(Name),1) = '"'
but looking for more reliable solution. This fails if any column has trailing white space
Just use REPLACE?
...
SET Name = REPLACE(Name,'"', '')
...
UPDATE Table
SET Name = REPLACE(Name, '"', '')
WHERE CHARINDEX('"', Name) <> 0
create table #t
(
Name varchar(100)
)
insert into #t(Name)values('"deded"')
Select * from #t
update #t Set Name = Coalesce(REPLACE(Name, '"', ''), '')
Select * from #t
drop table #t
Quick and Dirty, but it will work :-)
You could expand and write this as a store procedure taking in a table name, character you want to replace, character to replace with, Execute a String variable, etc...
DECLARE
#TABLENAME VARCHAR(50)
SELECT #TABLENAME = 'Locations'
SELECT 'Update ' + #TABLENAME + ' set ' + column_Name + ' = REPLACE(' + column_Name + ',''"'','''')'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #TABLENAME
and data_Type in ('varchar')

Convert SQL Server result set into string

I am getting the result in SQL Server as
SELECT StudentId FROM Student WHERE condition = xyz
I am getting the output like
StudentId
1236
7656
8990
........
The output parameter of the stored procedure is #studentId string and I want the return statement as
1236, 7656, 8990.
How can I convert the output in the single string?
I am returning single column [ie. StudentId]
Test this:
DECLARE #result NVARCHAR(MAX)
SELECT #result = STUFF(
( SELECT ',' + CONVERT(NVARCHAR(20), StudentId)
FROM Student
WHERE condition = abc
FOR xml path('')
)
, 1
, 1
, '')
DECLARE #result varchar(1000)
SELECT #result = ISNULL(#result, '') + StudentId + ',' FROM Student WHERE condition = xyz
select substring(#result, 0, len(#result) - 1) --trim extra "," at end
Use the COALESCE function:
DECLARE #StudentID VARCHAR(1000)
SELECT #StudentID = COALESCE(#StudentID + ',', '') + StudentID
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select #StudentID
Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL:
NULL + "Any text" => NULL
It's a very common mistake, don't forget it!
Also is good idea to use ISNULL function:
SELECT #result = #result + ISNULL(StudentId + ',', '') FROM Student
Use the CONCAT function to avoid conversion errors:
DECLARE #StudentID VARCHAR(1000)
SELECT #StudentID = CONCAT(COALESCE(#StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select #StudentID
The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...
ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286
original query...
SELECT StudentId FROM Student WHERE condition = xyz
original result set...
StudentId
1236
7656
8990
new query w/ concat...
SELECT group_concat(concat_ws(',', StudentId) separator '; ')
FROM Student
WHERE condition = xyz
concat string result set...
StudentId
1236; 7656; 8990
note: change the 'separator' to whatever you would like
GLHF!
This one works with NULL Values in Table and doesn't require substring operation at the end. COALESCE is not really well working with NULL values in table (if they will be there).
DECLARE #results VARCHAR(1000) = ''
SELECT #results = #results +
ISNULL(CASE WHEN LEN(#results) = 0 THEN '' ELSE ',' END + [StudentId], '')
FROM Student WHERE condition = xyz
select #results
The answer from brad.v is incorrect! It won't give you a concatenated string.
Here's the correct code, almost like brad.v's but with one important change:
DECLARE #results VarChar(1000)
SELECT #results = CASE
WHEN #results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE #results + ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
See the difference? :) brad.v please fix your answer, I can't do anything to correct it or comment on it 'cause my reputation here is zero. I guess I can remove mine after you fix yours. Thanks!
Use STRING_AGG:
SELECT STRING_AGG(sub.StudentId, ',') FROM
(select * from dbo.Students where Name = 'Test3') as sub
If you want to use e.g ORDER BY:
SELECT STRING_AGG(sub.StudentId, ',') WITHIN GROUP(Order by StudentId) FROM
(select * from dbo.Students where Name = 'Test3') as sub
or a single select statement...
DECLARE #results VarChar(1000)
SELECT #results = CASE
WHEN #results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
Assign a value when declaring the variable.
DECLARE #result VARCHAR(1000) ='';
SELECT #result = CAST(StudentId AS VARCHAR) + ',' FROM Student WHERE condition = xyz