Query display names - sql

I have a 2 columns in a SQL Server table.
One is characters like 'Attn: firstname lastname', and the other column has a number associated with that person.
I can't figure out how to query them so the info comes out as:
Lastname, Firstname - number

If you are in SQL Server you can do this
Select Col1 + ' - ' + Col2
From dbo.{Table}
Where {Conditions}
If you mean you need to drop the "attn:" you can do something like this
Select substring(Col1, 5,len(Col1)-5) + ' - ' + Col2
From dbo.{Table}
Where {Conditions}

Instead of hardcoding the index of ':', you can do something like this
SELECT REPLACE(RIGHT(Col1, (LEN(Col1) - CHARINDEX(':', Col1)-1)),' ',', ') + ' - ' + Col2
To test this you can run the following
DECLARE #column1string AS VARCHAR(30), #column2number AS VARCHAR(10)
SET #column1string = 'Attn: Firstname Lastname'
SET #column2number = '12345678'
SELECT REPLACE(RIGHT(#column1string, (LEN(#column1string) - CHARINDEX(':', #column1string)-1)),' ',', ') + ' - ' + #column2number

Related

Trim extra white space within column

I have the following select that is converting a name from Lastname, Firstname format into Firstname Lastname format. It seems to be adding extra white space between the first name and the last name
SELECT substring(D.NAME, charindex(',', replace(D.NAME, ' ', '')) + 1, len(D.NAME))
+ ' '
+ left(D.NAME, charindex(',', D.NAME) -1) AS First_Last
FROM TEST_TABLE D
Here are a few examples of the output I'm getting now:
Johnnyyy Smithsonnn
Kimmey Test1
Denise Stuffing
Desired Format (single space between first and last name):
Johnnyyy Smithsonnn
Kimmey Test1
Denise Stuffing
I tend to like this technique. In this example we use a rare replacement pattern of †‡, but you can use <> and ><
Note: The outer ltrim(rtrim( ... )) is optional, I keep it as a "just in case".
Example
Select NewValue = ltrim(rtrim(replace(replace(replace([Name],' ','†‡'),'‡†',''),'†‡',' ')))
From YourTable
Returns
NewValue
Johnnyyy Smithsonnn
Kimmey Test1
Denise Stuffing
Maybe there are names with or without , or with or without spaces after the ,, or other inconsistencies.
Anyway you can use ltrim(rtrim()) before concatenating:
select
case
when d.name like '%,%' then
ltrim(rtrim(substring(d.name, charindex(',', name) + 1, len(d.name))))
+ ' ' +
ltrim(rtrim(left(D.NAME, charindex(',', d.name) -1)))
when d.name like '% %' then
ltrim(rtrim(substring(d.name, charindex(' ', name) + 1, len(d.name))))
+ ' ' +
ltrim(rtrim(left(D.NAME, charindex(' ', d.name) -1)))
else ltrim(rtrim(d.name))
end AS First_Last
Try:
select ltrim(rtrim(left(D.NAME, charindex(',', D.NAME, 0) - 1)))
+ ' '
+ ltrim(rtrim(right(D.NAME, len(D.NAME) - charindex(',', D.NAME, 0))))
from TEST_TABLE D
This worked on some test data I used below:
insert into #Test ([Name]) values ('Johnnyyy, Smithsonnn')
insert into #Test ([Name]) values ('Kimmey, Test1')
insert into #Test ([Name]) values ('Denise, Stuffing')
Which gives the intended result:
Johnnyyy Smithsonnn
Kimmey Test1
Denise Stuffing
I think you intend to do the replace of spaces after extracting the name. So:
SELECT (replace(left(D.NAME, charindex(',', D.NAME + ',') + 1), ' ', '') +
' ' +
left(D.NAME, charindex(',', D.NAME + ',') - 1)
) AS First_Last
FROM TEST_TABLE D;
This also adds a comma for the charindex() so the comma is optional.

Add selected values from multi column into one column separated by ','

I want to select values from multiple columns into one column. I have 2 separate columns from which i want to get name,address,state,zip in following format in SQL Server 2008
Name (new line)
address,state,zip
Name (new line)
address,state,zip
Query:
select
name + char(13) + concat(address,',', state,',', zip)
from
tbl1
join
tbl2 on....
I am not able to get the desired output. I get concat is not a recognized built in function name.
You could use + operator and cast the zip field as varchar directly like this:
For example:
select 'Dara Singh' + char(13) + '1234 Main Street' + ',' + 'NY' + ','
+ cast(95825 as varchar(10))
This is how your query would look:
select name + char(13) + [address] + ',' + [state] + ',' + cast([zip] as varchar(10))
from tbl1 join tbl2 on....

concat two columns in sql

I have four columns on data gridview and want them to concat in sql and exporting it to txt file but everytime i export this is my result.
My result
0010000 01500 00000 0001600
output required
001000001500000000001600
SQL Query:
string stringSql = " SELECT distinct " +
"REPLACE(RIGHT('00'+CAST(CAST(bat.PCN_Charge* 100.00 AS INT) AS VARCHAR(5)),8) as CLAIMAMT, + RIGHT('0'+CAST(CAST([CFee] * 100 AS INT) AS VARCHAR(5)),5),' ','' )as CFEE," +
"REPLACE(RIGHT('00000'+CAST(CAST([Solictors Fees] AS INT) AS VARCHAR(5)),5), + RIGHT('000'+CAST(CAST(bat.PCN_Charge + [CFee]*100 AS INT) AS VARCHAR(5)),9),' ','') as TotalAMT " +
Judging from the manual:
Method 1: Concatenating two strings
SELECT 'FirstName' + ' ' + 'LastName' AS FullName
Method 2: Concatenating two Numbers
SELECT CAST(1 AS VARCHAR(10)) + ' ' + CAST(2 AS VARCHAR(10))
Method 3: Concatenating values of table columns
SELECT FirstName + ' ' + LastName
FROM AdventureWorks.Person.Contact
In your case, you should do the same, avoiding the space in between.
select first_column+' '+second_c+' '+third_c+' '+forth_c
from table_name
try it
declare #result varchar(500)
set #result = ''
select #result = #result +' '+first_c+' '+second_c+' '+third_c+' '+forth_c
from table_name
declare #a varchar(50)
set #a='0010000 01500 00000 0001600'
select replace(#a,' ','')
SEE DEMO

Test if a string contains at least 2 words in SQL

I have an sql request like :
SELECT *
FROM table
WHERE lower(title) LIKE lower('%It's a beautiful string i think%')
I need to check if at least 2 words in my string It's a beautiful string i think are contained in my field title... How can i do that ?
For example, if in my field title i have the string I think it's beautiful, This query should return me this object...
Thanks !
You could split your string into a temporary table (say, using something like this: http://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql/) and then do a join, with a count.
You could generate the following SQL statement dynamically:
SELECT title, count(*)
FROM
(
SELECT title
FROM table1
WHERE (' ' + lower(title) + ' ') LIKE lower('% It %')
UNION ALL
SELECT title
FROM table1
WHERE (' ' + lower(title) + ' ') LIKE lower('% s %')
UNION ALL
SELECT title
FROM table1
WHERE (' ' + lower(title) + ' ') LIKE lower('% a %')
UNION ALL
SELECT title
FROM table1
WHERE (' ' + lower(title) + ' ') LIKE lower('% beautiful %')
UNION ALL
SELECT title
FROM table1
WHERE (' ' + lower(title) + ' ') LIKE lower('% string %')
UNION ALL
SELECT title
FROM table1
WHERE (' ' + lower(title) + ' ') LIKE lower('% I %')
UNION ALL
SELECT title
FROM table1
WHERE (' ' + lower(title) + ' ') LIKE lower('% think %')
) AS table2
GROUP BY title
HAVING COUNT(*) >= 2
A stored procedure might be more efficient and you could have the whole job done on the server side.
You could use a function like this
CREATE FUNCTION [dbo].[CheckSentece] (#mainSentence varchar(128), #checkSentence varchar(128))
RETURNS NUMERIC AS
BEGIN
SET #mainSentence=LOWER(#mainSentence)
SET #checkSentence=LOWER(#checkSentence)
DECLARE #pos INT
DECLARE #word varchar(32)
DECLARE #count NUMERIC
SET #count=0
WHILE CHARINDEX(' ', #checkSentence) > 0
BEGIN
SELECT #pos = CHARINDEX(' ', #checkSentence)
SELECT #word = SUBSTRING(#checkSentence, 1, #pos-1)
DECLARE #LEN NUMERIC
//Simple containment check, better to use another charindex loop to check each word from #mainSentence
SET #LEN=(SELECT LEN(REPLACE(#mainSentence,#word,'')))
if (#LEN<LEN(#mainSentence)) SET #count=#count+1
SELECT #checkSentence = SUBSTRING(#checkSentence, #pos+1, LEN(#checkSentence)-#pos)
END
return #count
END
and get the number of words from second sentence contained in the first one

Combine First, Middle Initial, Last name and Suffix in T-SQL (No extra spaces)

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