Combine source column values into one destination column - sql

I have a source table which has the columns AreaCodeMobile + MobilePhoneNumber, AreaCodeHome + HomeNumber, AreaCodeOffice + OfficeNumber and I am wanting to combine these into one telephone column in my destination table. How would I accomplish this?

What are the data types of those columns? Also, is it any format that you are looking to save in destination column? If they are all int datatype, you need to use CAST to convert to varchar. For e.g.,
DECLARE #AreaCodeMobile int = 833, #MobilePhoneNumber INT = 7571256
DECLARE #areacodehome INT = 877, #homenumber INT = 2968997
DECLARE #areacodeoffice INT = 247 , #officenumber INT = 8658734
select CONCAT (
'Mobile Phone Number: ' , cast(#areacodemobile as varchar(50)) , cast(#MobilePhoneNumber as varchar(50))
,' Home Number: ', CAST(#areacodehome as varchar(50)) , cast(#homenumber as varchar(50))
,' Office Number: ', CAST(#areacodeoffice as varchar(50)) , cast(#officenumber as varchar(50))
)

Simply use CONCAT.
And use + to prefix a comma, or whatever separator you prefere.
SELECT t.*,
CONCAT(AreaCodeMobile,
', '+MobilePhoneNumber,
', '+AreaCodeHome,
', '+HomeNumber,
', '+AreaCodeOffice,
', '+OfficeNumber) AS [Telephones]
FROM YourTable t;
The trick here is that CONCAT will ignore NULL's.
But a + will result to NULL if a NULL is added.
So then no useless comma's are added for the null's.
Or you could also use CONCAT_WS, if your version of Sql Server supports it.
SELECT t.*,
CONCAT_WS(', ', AreaCodeMobile, MobilePhoneNumber, AreaCodeHome, HomeNumber, AreaCodeOffice, OfficeNumber) AS [Telephones]
FROM YourTable t;
So to update that column in your table, maybe something like this:
UPDATE YourTable
SET Telephones = CONCAT_WS(', ', AreaCodeMobile, MobilePhoneNumber, AreaCodeHome, HomeNumber, AreaCodeOffice, OfficeNumber)
WHERE Telephones IS NULL;

Related

How do you update table using local variables or user-defined functions?

I am trying to update my table with setting the "username" to be a product of "name".
Here is my example:
declare #username varchar(128)
-- create local table
declare #t table (name varchar(32), username varchar(32))
insert into #t(name, username) values ('Johnny Cash','')
-- update rows, set "username" to its correct value
;with mytable as (select * from #t)
update mytable
-- this is really messy, I want to use some local variables or a user-defined function here to compute the username...
set username = lower(substring(name, 0, charindex(' ', name)) + '.' + substring(name, charindex(' ', name)+1, len(name)))
-- select all rows so I can see them
;with mytable as (select * from #t)
select * from mytable
For each row, I want the username to be the same as name but with some modifications.
Is this possible?
To clarify, I want the row with name "Johnny Cash" to have a username "johnny.cash"
Simple update statement would also work, no need to use variable :
update #t
set username = replace(lower(name), ' ', '.')
EDIT :
If you want only single value to be update with help of variable then you can do :
select #username = replace(lower(name), ' ', '.')
from #t
where name = #username;

Variable declaration to store multiple values like full column value

I have an requirement where I have to store the column value into an declared variable is it possible anyways. I understand that an variable can store only single value and not multiple values. But in my case I need it badly.
What I have here is to set the column if date value which is in INT has to be converted into Date column and save it in that variable to compare it.
I have some column with values like below
"A(B_CD_EE_FF_DFE)_ERT"
So i have to remove those two bracktes and process.
Set #Variable= (SELECT replace (replace ( replace (SUBSTRING(TXMLFileName, CHARINDEX('(', TXMLFileName)
, CHARINDEX(')',TXMLFileName) - CHARINDEX(')', reverse (TXMLFileName)) ) , ')', '') ,'(' ,'') ,'.xml' , '')
from
tblXML )
Gives me error and below gives answer as I select only top 1.
Set #Variable= (SELECT top 1 replace (replace ( replace (SUBSTRING(TXMLFileName, CHARINDEX('(', TXMLFileName)
, CHARINDEX(')',TXMLFileName) - CHARINDEX(')', reverse (TXMLFileName)) ) , ')', '') ,'(' ,'') ,'.xml' , '')
from
tblXML )
SO is there any known solution... ????? Thanks in advance
A variable needn't just store a single value. You can create e.g. custom table types
CREATE TYPE MyCustomType AS TABLE (
MyCustomTypeId INT,
MyCustomValueColumn VARCHAR(100)
)
Or just declare a comparable table variable inline where needed.
declare #tblXML table (TXMLFileName varchar(50))
insert into #tblXML values
('A(B_CD_EE_FF_DFE)_ERT'),
('(EE_FF_DFE)_ERT'),
('A(B_CD_EE)')
declare #tmp varchar(max)
SET #tmp = ''
SELECT #tmp=#tmp+ replace (replace ( replace (SUBSTRING(TXMLFileName, CHARINDEX('(', TXMLFileName)
, CHARINDEX(')',TXMLFileName) -1 ) , ')', '') ,'(' ,'') ,'.xml' , '')+''' '''
from
#tblXML
select ''''+#tmp
or you don't want to single row use this
SELECT ''''+ replace (replace ( replace (SUBSTRING(TXMLFileName, CHARINDEX('(', TXMLFileName)
, CHARINDEX(')',TXMLFileName) -1 ) , ')', '') ,'(' ,'') ,'.xml' , '')+''''
from
#tblXML

Get the value of a column replacing the comma separator

How can I get each value of a column that has a comma separator in her value ?
Example:
ID ColumnUnified
1 12,34,56,78
2 80,99,70,56
What I want is a query to get the number without comma. If possible, in collumns.
12 34 56 78
This will work for any number of values http://beyondrelational.com/modules/2/blogs/70/posts/10844/splitting-delimited-data-to-columns-set-based-approach.aspx
The solution Madhivanan's link refers to is very creative, but I had a slight problem with it on SQL Server 2012 related to the name of one of the columns (Start). I've modified the code in his answer to use StartPos instead of Start for the column name.
I was not familiar with the system procedure spt_values, but I found a very informative description of the procedure here on SO for those who are interested in exactly how this solution works.
Finally, here's the (slightly) revised code from Madhivana's answer:
CREATE TABLE #test(id int, data varchar(100))
INSERT INTO #test VALUES (1,'This,is,a,test,string')
INSERT INTO #test VALUES (2,'See,if,it,can,be,split,into,many,columns')
DECLARE #pivot varchar(8000)
DECLARE #select varchar(8000)
SELECT #pivot = COALESCE(#pivot + ',', '') + '[col'
+ CAST(number + 1 AS VARCHAR(10)) + ']'
FROM master..spt_values
WHERE type = 'p'
AND number <= ( SELECT MAX(LEN(data) - LEN(REPLACE(data, ',', '')))
FROM #test
)
SELECT #select = '
select p.*
from (
select
id,substring(data, StartPos+2, endPos-StartPos-2) as token,
''col''+cast(row_number() over(partition by id order by StartPos) as varchar(10)) as n
from (
select
id, data, n as StartPos, charindex('','',data,n+2) endPos
from (select number as n from master..spt_values where type=''p'') num
cross join
(
select
id, '','' + data +'','' as data
from
#test
) m
where n < len(data)-1
and substring(data,n+1,1) = '','') as data
) pvt
Pivot ( max(token)for n in (' + #pivot + '))p'
EXEC(#select)
DROP TABLE #test

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')

Flatten SQL Server Table to a string

I have a table like:
ID | Value
----------------
1 | One
2 | Two
3 | Three
What I need to do is create a single string from these values, in the format:
'1: One, 2: Two, 3: Three'
I know how to do this using cursors, but it will be used as a column in a view, so it's not really a performant option.
Any pointers?
WITH T(ID,Value) AS
(
SELECT 1, 'One' UNION ALL
SELECT 2, 'Two' UNION ALL
SELECT 3, 'Three'
)
SELECT STUFF(
(SELECT ', ' + CAST(ID as varchar(11)) + ': ' + Value
FROM T
FOR XML PATH (''))
, 1, 2, '')
Have a look at something like
DECLARE #Table TABLE(
ID INT,
Value VARCHAR(20)
)
INSERT INTO #Table SELECT 1,'One'
INSERT INTO #Table SELECT 2,'Two'
INSERT INTO #Table SELECT 3,'Three'
SELECT STUFF(
(
SELECT ', ' + CAST(ID AS VARCHAR(MAX)) + ': ' + Value
FROM #Table
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
)
SELECT STUFF((
SELECT ' ' + CAST(ID AS VARCHAR(2)) + ': '+ Value
FROM dbo.Table
FOR XML PATH('')
), 1, 1, ''
) As concatenated_string
DECLARE #ans VARCHAR(max)
SET #ans=''
SELECT #ans = #ans + str(id)+':'+value FROM table
SELECT #ans
Change the max to 8000 if your version of SQL doesn't support it
I would simply not do this in the database if at all possible. It's not designed for formatting data in a certain way; let the calling application handle that.
In C# (assuming data is an instance of SqlDataReader):
var l = new List<string>();
while (reader.Read())
l.Add(string.Format("{0}: {1}", reader[0], reader[1]));
var s = string.Join(", ", l.ToArray());