SQL manipulation in SQL Server 2008 - sql

I have two columns LocationCity and LocationCountry. I need to concatenate them into a single column.
What I have now is :
select
LocationCity, LocationCountry
from
Location
This produces an output like:
Hitchin,England United Kingdom
But my desired output is :
Hitchin, England, UK
How to achieve this?

String Concatenation
For SQL 2012 or Above
For SQL Server 2012 or newer, you can use the CONCAT function
SELECT CONCAT(
REPLACE(LocationCity, ',', ', ')
, ', '
, LocationCountry
)
FROM Location
Under SQL 2012
For versions before SQL Server 2012, there is no CONCAT function, but you can use string concatenation:
SELECT (
REPLACE(LocationCity, ',', ', ')
+ ', '
+ LocationCountry
)
FROM Location
If LocationCity is nullable use the following query
SELECT (
ISNULL(
REPLACE(LocationCity, ',', ', ') + ', '
, ''
)
+ LocationCountry
)
FROM Location
If LocationCity must act as null if empty use the following query
SELECT (
ISNULL(
NULLIF(
REPLACE(LocationCity, ',', ', ')
, ''
) + ', '
, ''
)
+ LocationCountry
)
FROM Location
Transform LocationCountry to short form
This might require to add another table or another column (dirty way)
which contains the short form of your LocationCountry column.
Then you can concatenate it the same way as before.
If the data is contained in another table, you may have to put a JOIN
References
CONCAT Function
String Concatenation
Using JOINs
REPLACE Function

Related

SQL Server how to rename a column in a select statement?

SELECT
CONTACTPHONE1 AS CONTACTPHONE1Orin,
CONTACTPHONE2 AS CONTACTPHONE2Orin,
REPLACE(TRANSLATE(UPPER(CONTACTPHONE1), '()-.,/+', ' '), ' ', '') AS CONTACTPHONE1,
REPLACE(TRANSLATE(UPPER(CONTACTPHONE2), '()-.,/+', ' '), ' ', '') AS CONTACTPHONE2
INTO
[dbo].[gz_temp]
FROM
Auct_ABSENTEEBID
SELECT
CONTACTPHONE1Orin,
CONTACTPHONE2Orin,
CASE
WHEN ISNUMERIC(RIGHT(CONTACTPHONE1, 1)) = 0
THEN SUBSTRING([CONTACTPHONE1], 1 , LEN([CONTACTPHONE1]) - PATINDEX('%[0-9]%', REVERSE([CONTACTPHONE1])))
ELSE CONTACTPHONE1
END AS CONTACTPHONE1,
CASE
WHEN ISNUMERIC(RIGHT(CONTACTPHONE2, 1)) = 0
THEN SUBSTRING([CONTACTPHONE2], 1 , LEN([CONTACTPHONE2]) - PATINDEX('%[0-9]%', REVERSE([CONTACTPHONE2])))
ELSE CONTACTPHONE2
END AS CONTACTPHONE2
INTO
[dbo].[Auct_ABSENTEEBID_Phone_Cleaning]
FROM
[dbo].[gz_temp]
The question title may not be clear. What I want to do is to merge these two select statements together. The problem is when I substitute CONTACTPHONE1 with REPLACE(TRANSLATE(UPPER(CONTACTPHONE1), '()-.,/+', ' '), ' ', '') in the second select statement, it becomes super tedious. Is it possible to alias it so that I don't have to use two select statements?
SELECT ##Version
Microsoft Azure SQL Data Warehouse - 10.0.15669.0 Jul 14 2022 22:09:30 Copyright (c) Microsoft Corporation
Create a function with one input parameter, CONTACTPHONE, with one return statement:
REPLACE(TRANSLATE(UPPER(CONTACTPHONE), '()-.,/+', ' '), ' ', '')
Then, call the function like this functionName(CONTACTPHONE1) and functionName(CONTACTPHONE2) directly in your second query, instead of CONTACTPHONE1 and CONTACTPHONE2 respectively.

sql concatenation with blank cells

So I am extracting data from one table to another
SELECT *
LTRIM(ADRESSE + ',' + ADRESSE2) AS ADDRESS12
FROM [Homestore].[dbo].[CLIENT]
Issue is that if the cells are blank i still get a comma ,
I have tried using & instead of + but nvarchar is incompatible in the '&' operator. Any ideas how I only insert the comma if there is something to concatenate?
You want the equivalent of CONCAT_WS() in other databases. You can do this with STUFF() and some string logic in SQL Server:
SELECT c.*
STUFF( (COALESCE(',' + ADRESSE, '') +
COALESCE(',' + ADRESSE2, '') +
), 1, 1, ''
) AS ADDRESS12
FROM [Homestore].[dbo].[CLIENT] c;
This structure is convenient, because you can just add more COALESCE() expressions for more columns.
use case expression
SELECT *, LTRIM(ADRESSE + case when ADRESSE is not null then ',' end + ADRESSE2) AS ADDRESS12
FROM [Homestore].[dbo].[CLIENT]
use case when for null checking
SELECT *
LTRIM(ADRESSE + case when ADRESSE2 is not null then
',' else '' end + ADRESSE2) AS ADDRESS12
FROM [Homestore].[dbo].[CLIENT]

How can I CONCAT portions of three columns to one new column

I am trying to create a new column in my results that is made up on the first 3 characters of "PrimaryName", all of "VendorCity", and the first 5 characters of "VendorZip"
SELECT,VendorName
,replace(PrimaryVendorLocationName,' ','') as PrimaryName
,replace(PrimaryVendorLocationCity,' ','') as VendorCity
,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]
As you can see I also need to remove spaces to ensure a cleaner return. I would like to call the new column "NewVendorCode". So a record that originates like this:
R A Slack
Chicago Heights
60654-1234
Will return this:
RASChicagoHeights60654
You can use the following, using LEFT (MySQL / TSQL):
SELECT CONCAT(
LEFT(REPLACE(PrimaryVendorLocationName, ' ', ''), 3),
REPLACE(PrimaryVendorLocationCity, ' ', ''),
LEFT(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 5)
) FROM table_name
... or you can use SUBSTRING (MySQL / TSQL) (instead of LEFT):
SELECT CONCAT(
SUBSTRING(REPLACE(PrimaryVendorLocationName, ' ', ''), 1, 3),
REPLACE(PrimaryVendorLocationCity, ' ', ''),
SUBSTRING(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 1, 5)
) FROM table_name
Note: As you can see the SELECT querys work on MySQL and TSQL without change.
demo (MySQL): https://www.db-fiddle.com/f/wTuKzosFgkEuKXtruCTCxg/0
demo (TSQL): http://sqlfiddle.com/#!18/dbc98/1/1
You can use the following code:
SELECT VendorName+
replace(PrimaryVendorLocationName,' ','') +
replace(PrimaryVendorLocationCity,' ','') +
replace(PrimaryVendorLocationZipCode,' ','') as NewVendorCode
SELECT VendorName
,PrimaryName
,VendorCity
,VendorZip
,CONCAT(LEFT(PrimaryName,3),VendorCity,LEFT(VendorZip,5)) As NewVendorCode
FROM (
SELECT VendorName
,replace(PrimaryVendorLocationName,' ','') as PrimaryName
,replace(PrimaryVendorLocationCity,' ','') as VendorCity
,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]
)

Concatenate and format text in SQL

I need to concatenate the City, State and Country columns into something like City, State, Country.
This is my code:
Select City + ', ' + State + ', ' + Country as outputText from Places
However, because City and State allow null (or empty) value, what happen is, (for example) if the City is null/empty, my output will look like , Iowa, USA; or say the State is empty, then the output will look like Seattle, , USA
Is there anyway I can format the output and remove "unnecessary" commas?
Edited: Because of the requirements, I should not use any other mean (such as PL/SQL, Store Procedure) etc., so it has to be plain SQL statement
select
isnull(City, '') +
case when isnull(City, '') != '' then ', ' else '' end +
isnull(State, '') +
case when isnull(State, '') != '' then ', ' else '' end +
isnull(Country, '') as outputText
from
Places
Since adding a string with null will result null so if they are null (not empty string) this will give you teh desired result
Select isnull(City + ', ','') + isnull(State + ', ' ,'') + isnull(Country,'') as outputText from Places
Use the COALESCE (Transact-SQL) function.
SELECT COALESCE(City + ', ', '') + COALESCE(State + ', ', '')...
In SQL Server 2012 you can use CONCAT function:
select concat(City,', ',State,', ',Country ) as outputText from Places
Not elegant by any means...
first changes city, state,country to null values if blank
then interprets that value for null and adds a space before a comma
then replaces any space comma space ( , ) with empty set.
Query:
SELECT replace(coalesce(Replace(City,'',Null),' ') + ', ' +
coalesce(Replace(State,'',Null), ' ' + ', ' +
coalesce(replace(Country,''Null),''), ' , ','') as outputText
FROM Places
Assumes no city state or country will contain space comma space.

What is the best way to collapse the rows of a SELECT into a string?

In a SQL statement ( or procedure ) I want to collapse the rows of this table into a single comma delimited string.
simpleTable
id value
-- -----
1 "a"
2 "b"
3 "c"
Collapse to:
"a, b, c"
You can concatenate using an embedded 'set' statement in a query:
declare #combined varchar(2000)
select #combined = isnull(#combined + ', ','') + isnull(value,'')
from simpleTable
print #combined
(Note that the first isnull() initialises the string, and the second isnull() is especially important if there's any chance of nulls in the 'value' column, because otherwise a single null could wipe out the whole concatenation)
(edited code and explanation after comments)
Edit (ten years later):
SQL Server 2017 introduced the STRING_AGG() function which provides an official way of concatenating strings from different rows. Like other aggregation functions such as COUNT(), it can be used with GROUP BY.
So for the example above you could do:
select string_agg(value, ', ')
from simpleTable
If you had some other column and you wanted to concatenate for values of that column, you would add a 'group by' clause, e.g:
select someCategory, string_agg(value, ', ') as concatValues
from simpleTable
group by someCategory
Note string_agg will only work with SQL 2017 and above.
This will only work in MSSQL 2005+
select value + ',' from simpletable for xml path ('')
..one way to prevent the extra comma:
select case(row_number() over (order by id))
when 1 then value else ',' + value end
from simpletable
for xml path ('')
DECLARE #EmployeeList varchar(100)
SELECT #EmployeeList = COALESCE(#EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
SELECT #EmployeeList
Results:
1, 2, 4
This is based on #codeulike answer, but will prevent losing the portion of the string that gets concatenated before a null "value" is concatenated on.
declare #combined varchar(2000)
select #combined = isnull(#combined + ', ','') + ISNULL(value,'')
from simpleTable
print #combined