Trying to learn SQL - sql-server

I have a select statement that strings the name together. The issue is that I want to put a period after the middle initial but when it is blank the period is after the firstname. Here is the select
select LTrim(RTrim(FirstName + ' ' + Left(MiddleName,1))) + '. ' + LastName as FullName,

Just add a case
select LTrim(RTrim(FirstName + ' ' + case when isnull(MiddleName,'')='' then else Left(MiddleName,1))) + '. ' end + LastName as FullName,

You could test for the existance of the MiddleName and only include your period if its not null
SELECT
LTRIM(RTRIM(FirstName + ' ' + IIF(ISNULL(MiddleName,'')<>'',LEFT(MiddleName,1) + '.', ''))) + ' ' + LastName as FullName

Use Case statement to check if the string is not empty
select LTrim(RTrim(FirstName + ' ' + Left(MiddleName,1))) +
case when Left(MiddleName,1) <> '' then '. ' else '' end + LastName as FullName,

Related

TSQL IF Operator results invalid column

My objective, is to select the first available address. If there isn't a AddressCity, then I should select the AddressRegion, and if there is not a AddressRegion I should select the AddressCountry.
IF AddressCity IS NOT NULL
SELECT AddressName + ' is from ' + AddressCity
ELSE
IF AddressRegion IS NOT NULL
SELECT Address+ ' is from ' + AddressRegion
ElSE
IF AddressCountry IS NOT NULL
SELECT AddressName + ' is from ' + AddressCountry
FROM DBO.Address
When I execute it, I get Invalid column name 'AddressCity'
You want something like case or coalesce():
SELECT coalesce(AddressName + ' is from ' + AddressCity,
AddressName + ' is from ' + AddressRegion
AddressName + ' is from ' + AddressCountry
)
FROM DBO.Address;

How to combine FirstName, MiddleName, LastName, comma and suffix in SQL Server?

I am trying to combine FirstName, MiddleName, LastName then a comma and suffix.
An example here describes this:
Sno. FirstName MiddleName LastName Suffix Result
---------------------------------------------------------------
1. ROBERT NULL SMALLWOOD NULL ROBERT SMALLWOOD
2. KIRK NULL ROBERTS MR KIRK ROBERTS, MR
3. WILLIAM DARRELL WATTENBARGER Jr. WILLIAM DARRELL WATTENBARGER, MR
If there is no Suffix, then comma (,) should not be appended also there should be only one space after every column.
So far I tried
REPLACE(RTRIM(Coalesce(FirstName + ' ', '') + Coalesce(MiddleName + ' ', '') + Coalesce(LastName + ' ', '') + Coalesce(SuffixId + ' ', '')),' ',' ')
Now how should I add a comma before suffix in case if it only exists without using case.
Thanks
You can use CONCAT:
SELECT CONCAT(FirstName,' ',MiddleName + ' ' ,LastName,', '+NULLIF(Suffix,'')) [Result]
FROM dbo.YourTable;
Use ISNULL:
SELECT ISNULL(FirstName + ' ', '') + ISNULL(MiddleName + ' ', '') + ISNULL(LastName + ' ', '') + ISNULL(', ' + SuffixId, '')
FROM My_Table_Name
This is the solution I came up with, please try and see if that worked for you.
create table #FullNameCalculation
(
Sno int not null,
FirstName varchar(10),
MiddleName varchar(10),
LastName varchar(15),
Suffix varchar(5)
)
insert into #FullNameCalculation
(Sno,FirstName,MiddleName,LastName,Suffix)
values
(1, 'ROBERT', NULL,'SMALLWOOD', NULL),
(2, 'KIRK', NULL, 'ROBERTS', 'MR'),
(3,'WILLIAM', 'DARRELL', 'WATTENBARGER', 'JR.'),
(4,NULL,'BARBER','SINK','MS'),
(5,NULL,NULL,'SANDERS','MRS.'),
(6,'SARA',' D','WILLIAMS ',' MS');
SELECT * FROM #FullNameCalculation;
SELECT *,
RTRIM(LTRIM(CONCAT(RTRIM(LTRIM(FirstName)),' ',
RTRIM(LTRIM(MiddleName)),' ',
RTRIM(LTRIM(LastName)),
iif(RTRIM(LTRIM(Suffix)) IS NULL OR RTRIM(LTRIM(Suffix))='','',', '+RTRIM(LTRIM(Suffix)))))) AS FullName
FROM #FullNameCalculation;
I wanted to do something similar and I used COALESCE like OP. Using the suggestion from Mark Adelsberger my query looked like this:
SELECT
RTrim(Coalesce(FirstName + ' ', '')
+ Coalesce(MiddleName + ' ', '')
+ Coalesce(LastName + ' ', '')
+ Coalesce(', ' + Suffix, '')) FullName
FROM dbo.YourTable

SQL Stored Procedure How to Modify and Return the Result of an Executed Dynamic Query

I have created a stored procedure that returns a single string of concatenated fields. The issue is that some of these fields may be empty strings resulting in a string much like the below:
, Mendip Road, Farnborough, Hampshire, GU14 9LS
or even
, , Farnborough, Hampshire, GU14 9LS
I really want to strip off any leading commas but I'll only know this once the query has been executed. Is there a way of executing the query, pattern-matching the commas and then removing them before finally returning the modified string?
The query itself is as follows:
SET #SQLQuery = 'SELECT TOP 1 REPLACE((ISNULL(POI,'''') + '', '' + ISNULL(Name,'''') + '', '''
+ ' + ISNULL(Settlement,'''') + '', '' + ISNULL(Cou_Unit,'''') + '', '' + ISNULL(Postcode,'''')),'', , '', '', '')'
+ ' AS ClosestAddress FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] ORDER BY '
+ ' (Longitude ' + #LongitudeOperator + ' ' + CAST(ABS(#Longitude) AS VARCHAR(20)) + ')'
+ ' * (Longitude ' + #LongitudeOperator + ' ' + CAST(ABS(#Longitude) AS VARCHAR(20)) + ')'
+ ' + (Latitude - ' + CAST(#Latitude AS VARCHAR(20)) + ') * (Latitude - ' + CAST(#Latitude AS VARCHAR(20)) + ') ASC'
EXECUTE(#SQLQuery)
Concatenate the comma inside the ISNULL expression as follows:
ISNULL(POI + ', ','')
so your query will look like:
SET #SQLQuery = 'SELECT TOP 1 REPLACE((ISNULL(POI + '', '','''') + ISNULL(Name + '', '','''')'
+ ' + ISNULL(Settlement + '', '','''') + ISNULL(Cou_Unit + '', '','''') + ISNULL(Postcode,'''')),'', , '', '', '')'
+ ' AS ClosestAddress FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] ORDER BY '
+ ' (Longitude ' + #LongitudeOperator + ' ' + CAST(ABS(#Longitude) AS VARCHAR(20)) + ')'
+ ' * (Longitude ' + #LongitudeOperator + ' ' + CAST(ABS(#Longitude) AS VARCHAR(20)) + ')'
+ ' + (Latitude - ' + CAST(#Latitude AS VARCHAR(20)) + ') * (Latitude - ' + CAST(#Latitude AS VARCHAR(20)) + ') ASC'
I don't know if you need dynamic SQL for some other reason, but I think something like this should work (with no Dynamic SQL); if you're really sure you need Dynamic SQL for some other reason, then just refactor this idea into your Dynanmic Statement:
DECLARE #ClosestAddress VARCHAR(1000)
SELECT TOP 1
#ClosestAddress = ISNULL(POI + ', ','')
+ ISNULL(Name + ', ','')
+ ISNULL(Settlement + ', ','')
+ ISNULL(Cou_Unit + ', ', '')
+ ISNULL(Postcode,'')
--AS ClosestAddress
FROM [UKStreetsAndPlaces].[dbo].[OS_Locator] ORDER BY (Longitude = 12.2132) * (Longitude = 12.2132) + (Latitude - 12.2132) * (Latitude - 12.2132) ASC
IF (RIGHT(#ClosestAddress, 2) = ', ')
RETURN SUBSTRING(#ClosestAddress, 0, LEN(#ClosestAddress))
ELSE
RETURN #ClosestAddress
Why this should work: Concatenating NULL + ', ' will result in an empty string. Then we check if the string ends with ', ', and if so we return everything but the last two characters.
You could do something like Replace all Comma with space and then do LTRIM and RTRIM and replace all space with comma.
Create table Data(name varchar(10),lastname varchar(10));
insert into Data values('','Doe');
insert into Data values('Jane','Doe');
insert into Data values('Jane','');
SELECT Replace(Rtrim(Ltrim(Replace(ISNULL(name,'') +',' + ISNULL(lastname,'') + ',',',',' '))),' ',',')
from Data
something like : http://sqlfiddle.com/#!3/6a6c6/1

Can someone please help me understand the case function?

I am working in SQL data base. I have to make two columns. The first column is the length of the employee name(I have that) The second column is title of courtesy and then the last name of employee.
My problem is how do i add the case function to have Ms displayed as miss, mr. as mister and dr as doctor. I do not understand. Any help would be appreciated. Here is the code i have so far:
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name]
, TitleOfCourtesy + LastName AS Title
FROM dbo.Employees
You can do something like this:
select
... your previous things here ...
case TitleOfCourtesy
when 'Mr' then 'Mister '
when 'Ms' then 'Miss '
when 'Dr' then 'Doctor '
else '' end + LastName as Title
try this
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name],
CASE
WHEN TitleOfCourtesy = 'Ms' THEN 'Miss '
WHEN TitleOfCourtesy = 'Mr' THEN 'Mister '
WHEN TitleOfCourtesy = 'dr' THEN 'Doctor ' END + LastName AS Title
FROM dbo.Employees
Thanks all I fixed it I had to add the period after like mr.
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name]
, CASE TitleOfCourtesy
WHEN 'Mr.' THEN 'Mister '
WHEN 'mrs. ' THEN 'Miss'
WHEN 'Ms.' THEN 'Miss '
WHEN 'Dr.' THEN 'Doctor '
ELSE '' END
+ TitleOfCourtesy + LastName
AS title
FROM dbo.Employees

Correct Amount of Spaces with concatenated person's name in SQL Server

Here is my SQL as I have it now. The first and last name should never be missing because they are required on the interface with validation. However, if the middle initial is missing, I don't want two spaces in the result; I just want one space. I could put a case statement in, but that seems like overkill if SQL already has a function for this purpose. Does anyone know if there is a function for this purpose? What would the code look like?
SELECT ISNULL(contact.firstname, '')
+ ' '
+ ISNULL(contact.middleinitial, '')
+ ' '
+ ISNULL(contact.lastname, '')
FROM dbo.contact
SELECT
ISNULL(contact.firstname, '') +
ISNULL(' ' + contact.middleinitial + ' ', ' ') +
ISNULL(contact.lastname, '')
However, you either should remove ISNULL for firstname, lastname (defined NOT NULL?) or add some trims
SELECT
LTRIM(RTRIM(
ISNULL(contact.firstname, '') +
ISNULL(' ' + contact.middleinitial + ' ', ' ') +
ISNULL(contact.lastname, '')
))
In SQL Server 2012 and up you can use CONCAT function:
SELECT CONCAT(contact.firstname, ' ' + contact.middleinitial, ' ' + contact.lastname)
FROM dbo.contact
If middleinitial is null then appending space to null value will result in null value and CONCAT will skip this null value during concatenation.
SELECT REPLACE(ISNULL(contact.firstname, '') + ' ' + ISNULL(contact.middleinitial, '') + ' ' + ISNULL(contact.lastname, '')
,' ',' ')
FROM dbo.contact

Resources