I want to create a view from a table where we have a FirstName, LastName and MiddleName column and where the MiddleName might be NULL, plus a salary. I need to replace the MiddleName with and empty string where there's not MiddleName. I'm using SQL Management Studio.
I came up with this code:
CREATE VIEW V_EmployeeNameJobTitle AS
SELECT FirstName + ' ' + MiddleName + ' ' + LastName AS [Fullname], Salary FROM Employees WHERE MiddleName IS NOT NULL
UNION SELECT FirstName + ' ' + LastName AS [Fullname], Salary FROM Employees WHERE MiddleName IS NULL
But this doesn't seem to work as I wanted to, and it's not very pretty. Any other suggestions how I might shorten this. Thanks in advance.
Use the ISNULL() function, where it replaces the NULL value int the value you choose. for ex:
CREATE VIEW V_EmployeeNameJobTitle AS
SELECT FirstName + ' ' + ISNULL(MiddleName, '') + ' ' + LastName AS [Fullname], Salary
FROM Employees
or if you don't want to get 2 spaces when the middle name is null, you can undergo the following:
CREATE VIEW V_EmployeeNameJobTitle AS
SELECT (CASE WHEN MiddleName IS NULL THEN FirstName + ' ' + LastName
ELSE FirstName + ' ' + MiddleName + ' ' + LastName END) AS [Fullname],
Salary
FROM Employees
SELECT FirstName + ' ' +
(case when MiddleName is null then '' else MiddleName + ' ' end) +
LastName AS [Fullname]
use IsNull function
CREATE VIEW V_EmployeeNameJobTitle AS
SELECT FirstName + ' '
+ MiddleName + ' '
+ IsNull(LastName, '') AS [Fullname]
, Salary
FROM Employees
Related
This is my query:-
select
(FirstName + ' ' + Lastname) as [Name]
from
c_client
where
MiddleInitial is null
union
select
(FirstName + ' ' + MiddleInitial + '''' + Lastname) as [Name]
from
c_client
where
MiddleInitial is not null
After executing it, I'm getting this output:
This is my new table:
CREATE TABLE AddData(Name VARCHAR(MAX))
I want to insert the result generated by the SELECT query into my new table AddData. Can you help me do this?
You would use insert:
insert into AddData (Name)
Select (FirstName + ' ' + Lastname) as [Name]
from c_client
where MiddleInitial IS NULL
UNION
Select (FirstName + ' ' + MiddleInitial +''''+ Lastname) as [Name]
from c_client
where MiddleInitial IS NOT NULL;
I would instead suggest writing the logic as :
select (FirstName +
coalesce(MiddleInitial + '''', '') +
' ' +
Lastname
) as Name
into AddData
from c_client c;
You won't have to create the table first.
Also, if you do want to remove duplicates then use select distinct. It is not clear if you are using union intentionally to remove duplicates or just to combine two separate subqueries.
I am trying to add a computed column to an SQL database. The Computed Column Specification looks like this
BusinessName + ' ' + Surname + ' ' + FirstName
which works fine.
Often the BusinessName is blank so I want to Trim it
Trim(BusinessName + ' ' + Surname + ' ' + FirstName)
But when I do I get an error
You can use below logic,
First option: check if value is null, replace it by empty string, you will have leading empty space if BusinessName is null
isnull(BusinessName, '') + ' ' + Surname + ' ' + FirstName
or
Second option: check if BusinessName is empty or null, do not take into account if so. You won't have leading empty space if BusinessName is null or empty
case when isnull(BusinessName, ' ') <> ' '
then BusinessName + ' ' + Surname + ' ' + FirstName
else Surname + ' ' + FirstName
end as FullName
I think it depends by column datatypes and constraints. A more general approach could be the following. Starting from this if as a rule SURNAME and NAME (for instance) are not NULLABLE and cannot be blank, you can omit some of the functions:
DECLARE #T AS TABLE (BUSIN_NAME VARCHAR(20), SURNAME VARCHAR(20), NAME VARCHAR(20))
INSERT INTO #T VALUES(NULL, NULL, NULL);
INSERT INTO #T VALUES(NULL, 'A', NULL);
INSERT INTO #T VALUES(NULL, 'B ', NULL);
INSERT INTO #T VALUES('', 'Karl ', ' Smith');
INSERT INTO #T VALUES('Dr.', 'Karl ', ' Smith');
INSERT INTO #T VALUES('Dr. ', 'Joe ', ' Martin ');
SELECT BUSIN_NAME, SURNAME, NAME
, LTRIM(RTRIM( LTRIM(RTRIM(ISNULL(BUSIN_NAME,'')))+ ' ' + LTRIM(RTRIM(ISNULL(SURNAME,'')))+' ' +LTRIM(RTRIM(ISNULL(NAME,''))))) DESCR
, DATALENGTH ( LTRIM(RTRIM( LTRIM(RTRIM(ISNULL(BUSIN_NAME,'')))+ ' ' + LTRIM(RTRIM(ISNULL(SURNAME,'')))+' ' +LTRIM(RTRIM(ISNULL(NAME,''))))) ) AS LENGTH
FROM #T
OUtput:
BUSIN_NAME SURNAME NAME DESCR LENGTH
NULL NULL NULL 0
NULL A NULL A 1
NULL B NULL B 1
Karl Smith Karl Smith 10
Dr. Karl Smith Dr. Karl Smith 14
Dr. Joe Martin Dr. Joe Martin 14
I would suggest doing the following:
select stuff( (coalesce(' ' + BusinessName, '') +
coalesce(' ' + Surname, '') +
coalesce(' ' + Firstname, '')
), 1, 1, '')
These easily generalizes to more fields. You can use ltrim() rather than stuff(), because you are using spaces as a separator. stuff() is more general, because it handles other separators (notably commas).
As a computed column:
alter table t add newcol as
(stuff( (coalesce(' ' + BusinessName, '') +
coalesce(' ' + Surname, '') +
coalesce(' ' + Firstname, '')
), 1, 1, ''
)
)
I have a query where the first column display name length the second is title or courtesy I have done those but I'm having trouble with my third column. It is supposed to use substring and display first name initial and last name initial can anyone tell me how to add this function to what I already have?
Here is the query
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
(since you used LEN I assume you are using SQL Server)
You mean something like this?
substring(FirstName,1,1) + substring(LastName,1,1)
In general it is like this :
substring(expression, startPosition, lenght)
I would use LEFT() instead of substring.
DECLARE #Employees TABLE (FirstName VARCHAR(25),LastName VARCHAR(25), TitleOfCourtesy VARCHAR(5))
INSERT INTO #Employees
VALUES ('Bob','Brown','Mr.'),
('Olivia','Taylor','M rs.'),
('Grace','Stevens','Ms.'),
('Theodor','Seuss','Dr.');
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name],
CASE Replace(TitleOfCourtesy, ' ','') --Gets rid of any white space
WHEN 'Mr.' THEN 'Mister'
WHEN 'mrs.' THEN 'Miss'
WHEN 'Ms.' THEN 'Miss'
WHEN 'Dr.' THEN 'Doctor'
ELSE ''
END + ' ' + LastName AS title,
CONCAT(LEFT(FirstName,1),'.',LEFT(LastName,1),'.') AS Initials
FROM #Employees
Results:
Length of Employee Name title Initials
-------------------------------------------- -------------------------------- --------
Your full name is 8 character(s). Mister Brown B.B.
Your full name is 12 character(s). Miss Taylor O.T.
Your full name is 12 character(s). Miss Stevens G.S.
Your full name is 12 character(s). Doctor Seuss T.S.
I have a SQL Search Query which works if I search on the First Name or the Surname:
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName + Surname LIKE N'%' + 'Smith' + '%'
ORDER BY FullName
If I search for John I see all John's if I search for Smith I see all Smith's What I would like is to search for John Smith and see all John Smith's. Thanks
UPDATE:
I should have made my original post clearer. I am using vb.net and when the user enters a search term into a text box the actual query that is run is as follows:
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName + Surname LIKE N'%' + #SearchTerm + '%'
ORDER BY FullName
I want the user to be able to type: John S and see all users called John with a Surname of S.
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName LIKE '%john%'
AND Surname LIKE '%smith%'
ORDER BY FullName;
Based on the caveats and conditions in your comments on other questions, your best bet is going to be have two search boxes (firstname and surname) and build a query that looks something like this.
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName like N'%' + #SearchFirst + '%' AND
Surname LIKE N'%' + #SearchSurname + '%'
ORDER BY FullName
Alternatively you could try to manually parse a single search box into first and last name before inserting the values into your query. But parsing names is a very dicey affair not entered into lightly.
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName + Surname LIKE N'%' + 'Smith' + '%'
ORDER BY FullName
Okie, I'mma try to take a crack at this. Assuming that you want to search for last and first name.
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName='John' AND Surname='Smith'
ORDER BY FullName
Would this work?
Unless you have data like this:
Firstname | Lastname
John Stewart | Mill
your query above with Searchterm = '%John M%' will find all the Johns whose surname begins with M, provided that you concatenate a space:
where firstname + ' ' + lastname like '%John S%'
However you won't get great performance with CONTAINS-SUBSTRING type queries (i.e. wildcard on either side of the search term). Starts-with queries can make use of an index, so it would better to write:
where firstname = 'John' -- can use an index on firstname column
and lastname like 'S%' -- can use an index on lastname column
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName + ' ' + Surname LIKE N'%' + SearchTerm + '%'
ORDER BY FirstName
Here SearchTerm could be any
John Smith,
Or
John S,
Or
John,
Or simply
J
I'm trying not to reinvent the wheel here...I have these four fields:
[tbl_Contacts].[FirstName],
[tbl_Contacts].[MiddleInitial],
[tbl_Contacts].[LastName],
[tbl_Contacts].[Suffix]
And I want to create a FullName field in a view, but I can't have extra spaces if fields are blank...
So I can't do FirstName + ' ' + MiddleInitial + ' ' + LastName + ' ' + Suffix... Because if there is no middle initial or suffix I'd have 2 extra spaces in the field. I think I need a Case statement, but I thought someone would have a handy method for this...Also, the middleinitial and suffix may be null.
Assuming that all columns could be nullable, you can do something like:
RTrim(Coalesce(FirstName + ' ','')
+ Coalesce(MiddleInitial + ' ', '')
+ Coalesce(LastName + ' ', '')
+ Coalesce(Suffix, ''))
This relies on the fact that adding to a NULL value yields a NULL.
Whichever options you choose, here's something to think about: this will be a rather involved and thus time consuming option, especially if you have it in a view which gets evaluated each and every time for each and every row in question.
If you need this frequently, I would recommend you add this to your base table as a persisted, computed field - something like:
ALTER TABLE dbo.tbl_Contacts
ADD FullName AS (insert the statement of your choice here) PERSISTED
When it's persisted, it becomes part of the underlying table, and it's stored and kept up to date by SQL Server. When you query it, you get back the current value without incurring the cost of having to concatenate together the fields and determine which to use and which to ignore...
Just something to think about - something that too many DBA's and database devs tend to ignore and/or not know about....
You may want to pass the FirstName + ' ' + MiddleInitial + ' ' + LastName + ' ' + Suffix concatenation through the REPLACE() function in order to substitute duplicate spaces into a single space.
REPLACE(FirstName + ' ' + MiddleInitial + ' ' + LastName + ' ' + Suffix, ' ', ' ')
-- -- -
EDIT:
Just noticed that some of your fields may be NULL, and therefore the above would not work in that case, as the whole string would become NULL. In this case, you can use the COALESCE() method as suggested by Thomas, but still wrapped it in a REPLACE():
REPLACE(RTRIM(COALESCE(FirstName + ' ', '') +
COALESCE(MiddleInitial + ' ', '') +
COALESCE(LastName + ' ', '') +
COALESCE(Suffix, '')), ' ', ' ')
Test:
SELECT REPLACE(RTRIM(COALESCE('John' + ' ', '') +
COALESCE('' + ' ', '') +
COALESCE('Doe' + ' ', '') +
COALESCE(NULL, '')), ' ', ' ')
-- Returns: John Doe
I had to join Firstname, Middlename, and Lastname. my challenge was to handle NULL values, used following code.
RTRIM(LTRIM(RTRIM(isnull(#firstname,'') + ' ' + isnull(#middlename,'')) + ' ' + isnull(#lastname,'')))
Test different scenarios if you are interested :)
DECLARE #firstname VARCHAR(MAX)
DECLARE #middlename VARCHAR(MAX)
DECLARE #lastname VARCHAR(MAX)
set #firstname = 'FirstName'
set #middlename = NULL
set #lastname = 'LastName'
SELECT '|'+RTRIM(LTRIM(RTRIM(isnull(#firstname,'') + ' ' + isnull(#middlename,'')) + ' ' + isnull(#lastname,'')))+'|'
--
If you are using SQL Server 2012+ you could use CONCAT and +:
SELECT RTRIM(
CONCAT(FirstName + ' ', MiddleInitial + ' ', LastName + ' ', Suffix)
) AS [FullName]
FROM tbl_Contacts;
How it works:
If any part of full name is NULL then NULL + ' ' → NULL
CONCAT handles NULL
In case that after part of name there are only NULLs, TRIM last space.
LiveDemo
Here is a solution:
CREATE FUNCTION dbo.udf_IsNullOrEmpty
(
#vchCheckValue VARCHAR(MAX)
,#vchTrueValue VARCHAR(MAX)
,#vchFalseValue VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN CASE WHEN NULLIF(RTRIM(LTRIM(#vchCheckValue)),'') IS NULL THEN #vchTrueValue ELSE #vchFalseValue END
END
SELECT FirstName + ' ' +
dbo.udf_IsNullOrEmpty(MiddleInitial,'',MiddleInitial + ' ') +
LastName +
dbo.udf_IsNullOrEmpty(Suffix,'',' ' + Suffix)
FROM tbl_Contacts
select CONCAT(IFNULL(FirstName, ''),
'',
IFNULL(MiddleName, ''),
'',
IFNULL(LastName, '')) AS name
from table
Why not like this:
select concat(fName,' ',
case length(mName)
when 0 then ''
else concat(mName, ' ') end, lName) as fullName
My columns are not null, so this works for me.
create function getfname(#n varchar(30))
returns varchar(30)
as
begin
declare #s varchar(30)
set #s=LEFT(#n,charindex(' ',#n)-1)
return #s
end
create function getLname(#n varchar(30))
returns varchar(30)
as
begin
declare #s varchar(30)
set #s=substring(#n,charindex(' ',#n+1),Len(#n))
return #s
end
the query:
SELECT retire.employeehrmsid,
Isnull(retire.firstname, '') + ' '
+ Isnull(retire.middlename, '') + ' '
+ Isnull(retire.lastname, '') AS FullName,
retire.dojtoservice,
retire.designation,
emphistory.currentdoj,
emphistory.presentddo,
emphistory.office,
transfer.generatetid AS TransferID,
transfer.transferdate,
transfer.currentlocation,
transfer.newlocation,
transfer.datas AS Transfer_Doc,
release.generaterid AS ReleaseID,
release.releasedate,
release.datar AS Release_Doc,
employeeserviceupdate.dataeu AS Join_Doc
FROM retire
INNER JOIN emphistory
ON retire.id = emphistory.id
INNER JOIN employeeserviceupdate
ON retire.id = employeeserviceupdate.id
INNER JOIN transfer
ON retire.id = transfer.id
AND emphistory.ehrid = transfer.ehrid
INNER JOIN release
ON transfer.tid = release.tid