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

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.

Related

Incorporate case statement in where clause

My requirement is as follows: I need to extract all companies data, which has similar name in table (first 3 words should occur in the name,can be in middle) as the input company name.
My query is working fine for data where name has more than 3 words ,but for less or equal to 3 it's failing.
I didn't get how to incorporate conditions in where clause.
My query is as below
select regno,name from ereg
where
(name like '%' +(
SELECT SUBSTRING(name, 0, CHARINDEX(' ', name, CHARINDEX(' ', name, CHARINDEX(' ', name, 0)+1)+1)) matchingwrd
FROM ereg where regno='C2113-UPD01')+'%')
script is as below
CREATE TABLE ereg(
regnoINT, name VARCHAR(50)
);
INSERT INTO ereg (regno,name)
values
('C2113-UPD01','future company Ltd'),
('C2223-UPD01','MY future company Ltd Corp'),
('C2113-UPD01','Prime Private Furnishings housing Ltd '),
('C26903-UPD01','My Prime Private Furnishings Service '),
for example,its working fine for regno='C2113-UPD01' and gives output -->>'C26903-UPD01','My Prime Private Furnishings Service
but if input is 'C2113-UPD01' My query fails and not able to fetch 'C2223-UPD01' company data
Your table data insert script, the data and the script all seems to be not taken from a working version. I had to clean everything.
What I did to get the 3 words is adding another space in front of the name:
Still your query gave me trouble. But here is how I did that
;With cted as
(
Select regno, name,
SUBSTRING(name + ' ', 0, CHARINDEX(' ', name + ' ', CHARINDEX(' ', name + ' ', CHARINDEX(' ', name + ' ', 0)+1)+1)) as ThreeWords
from ereg
)
Select c1.regno, c1.name, c2.regno, c2.name
from cted c1
inner join cted c2 on c2.name like '%' + c1.ThreeWords + '%' and c1.regno <> c2.regno
Where c1.regno='C2213-UPD01' -- or c1.regno='C2113-UPD01'
Here is the fiddle

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

I'm having an issue with syntax in a Stored SQL Procedure

I'm trying to add three additional columns to a stored procedure (I don't have a lot of experience in stored procedures), the columns are Family ID, Address, and Phone No. Although I've run the query and confirmed the syntax for my select statement is correct, when I add the statement to the stored proc, I receive the following error: Incorrect syntax near 'capPrograms'(this would be line 14). I know this probably has to do with hoe I'm trying to implement my statement in the procedure to update it, but I'm not quite sure what the issues as I've tried several changes with similar or more extensive errors. Any assistance is appreciated, I've included the block of code I'm working with below:
SELECT capCase.Id AS capCase_Id,
capCase.DateApplied AS capCase_DateApplied,
CASE
WHEN ISNUMERIC(#cases.origCaseYear)=1 THEN CAST(origCaseYear + 2004 AS VARCHAR) + ' - ' + CAST(capCase.IdYear + 2004 AS VARCHAR)
WHEN #cases.maxRolloverYear IS NOT NULL THEN CAST(capCase.IdYear + 2004 AS VARCHAR) + ' - ' + CAST(#cases.MaxRolloverYear + 2004 AS VARCHAR)
ELSE CAST(capCase.IdYear + 2004 AS VARCHAR)
END AS capCase_IdYear,
Person.id as Person_id,
Person.LastName + ', ' + Person.FirstName AS PersonPrint_Name,
person.idFamily AS Family_ID, person.homePhone AS Phone_No, (SELECT family.physicalAddress1+ ', ' + family. physicalAddressCity+ ' ' +family. physicalAddressZip) AS Address
FROM Family
LEFT JOIN person ON family.Id = person.idFamily;
capPrograms.Program AS capPrograms_Program,
capStatus.Status AS capStatus_Status,
#lastFollowup.followupDate AS capCaseFollowup_Date,
CASE
WHEN capCase.IdCaseWorker IS NULL THEN 'No Worker Assigned'
ELSE caseWorker.LastName + ', ' + caseWorker.FirstName + ISNULL('<' + caseWorker.EmailWork + '>', '')
END AS capCase_IdCaseWorker,
capcaseDenialReason.reason AS capCase_idDenialReason,
Too long to comment, so I added a bunch of comments in your code. You have, A LOT of issues.
SELECT
capCase.Id AS capCase_Id,
capCase.DateApplied AS capCase_DateApplied,
CASE
--here you are referencing a temp table, which isn't joined below
WHEN ISNUMERIC(#cases.origCaseYear)=1 THEN CAST(origCaseYear + 2004 AS VARCHAR) + ' - ' + CAST(capCase.IdYear + 2004 AS VARCHAR)
WHEN #cases.maxRolloverYear IS NOT NULL THEN CAST(capCase.IdYear + 2004 AS VARCHAR) + ' - ' + CAST(#cases.MaxRolloverYear + 2004 AS VARCHAR)
ELSE CAST(capCase.IdYear + 2004 AS VARCHAR)
END AS capCase_IdYear,
Person.id as Person_id,
Person.LastName + ', ' + Person.FirstName AS PersonPrint_Name,
person.idFamily AS Family_ID,
person.homePhone AS Phone_No,
--this subquery as no from clause... that's an issue... you probably want to remove it completly and replace it with the one below
(SELECT family.physicalAddress1+ ', ' + family. physicalAddressCity+ ' ' +family. physicalAddressZip) AS Address,
--this is likely what you want
family.physicalAddress1 + ', ' + family. physicalAddressCity + ' ' + family. physicalAddressZip AS AddressCorrected
FROM Family
LEFT JOIN person ON
family.Id = person.idFamily; --you have a ; here, which terminates the statement. Everything else below isn't included
--Here you need to join the capPrograms and #lastFollowup table..
--here, you listed some columns, without a table reference. You need to join the table above, and move these columns above the FROM clause
capPrograms.Program AS capPrograms_Program,
capStatus.Status AS capStatus_Status,
#lastFollowup.followupDate AS capCaseFollowup_Date,
CASE
WHEN capCase.IdCaseWorker IS NULL THEN 'No Worker Assigned'
ELSE caseWorker.LastName + ', ' + caseWorker.FirstName + ISNULL('<' + caseWorker.EmailWork + '>', '')
END AS capCase_IdCaseWorker,
capcaseDenialReason.reason AS capCase_idDenialReason,

SQL manipulation in SQL Server 2008

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

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.