How to compare right and left side of a string in SQL - sql-server

The idea is that if the first name and the last name are the same, the column indicator should put a 'fail' and if not, should enter 'pass'
SELECT TOP 1000
name,
case when CHARINDEX(' ',=name)<>0
and LEFT(TRIM(=name),CHARINDEX(' ',=name)-1)=RIGHT(TRIM(=name),CHARINDEX(' ',c=name)+1) then 'fail'
else 'pass' end AS indicator
FROM Table
I have an entry in the column name that is N/A N/A and I think it should fail with the case I wrote but is giving me a 'pass' I am not sure what could be the problem here

This worked for me, splitting like I usually do it. Although names may not have only one space in them.
with tbl(name) as (
select 'Darth Vader' union all
select 'N/A N/A' union all
select 'joe mama'
)
SELECT name,
case
when SUBSTRING(name,0,CHARINDEX(' ',name)) = SUBSTRING(name,CHARINDEX(' ',name)+1,LEN(name)) then 'fail'
else
'pass'
end AS indicator
FROM tbl;

I think you can just write something simple like this:
CREATE TABLE #TEMP_NAME
(
FIRSTNAME VARCHAR(50),
LASTNAME VARCHAR(50)
)
INSERT INTO #TEMP_NAME
SELECT 'FIRST', 'FIRST'
SELECT 'LAST', 'FIRST'
SELECT
CASE
WHEN PN.FIRSTNAME = PN.LASTNAME THEN 'FAIL'
WHEN PN.FIRSTNAME <> PN.LASTNAME THEN 'PASS'
END AS NAME_PASS_FAIL
FROM #TEMP_NAME PN
query result

Related

check if value in column is date, and then do something with it

I have a column that holds a rejected reason for a person.
The value is either something like "Person refused" or "10/18/2012"
I'm trying to setup my query to check if the value is a date, then it can put a blank space in its place. Otherwise, keep the text that's in there.
The query that I setup is:
SELECT DISTINCT person_id,
CASE description
WHEN ISDATE(description) THEN ''
END AS refuseReason
FROM person
But this returns an error. If the dates themselves are saved as VARCHAR, then would I have to convert them first to a date, then check to see if ISDATE? If I did that, would it convert the text when it comes accross that?
EDIT: I tried it by casting it to datetime, and i keep getting error as well:
SELECT DISTINCT person_id,
CASE description
WHEN ISDATE(CAST(OBSVALUE AS DATETIME)) THEN ''
END AS refuseReason
FROM person
(Assuming TSQL) IsDate() returns 1 or 0. (Also your CASE syntax was incorrect)
Try:
SELECT DISTINCT person_id,
CASE
WHEN ISDATE(description) = 1 THEN ''
ELSE description
END AS refuseReason
FROM person
The ISDATE() functions returns a boolean 1 or 0
you have to make the clause by using
WHEN ISDATE(#variable) = 1 THEN ''
ELSE #variable

T-SQL needing to select results using 3 parameters and if any one doesnt exist in data correct inform user which one

I am looking to select from three columns using three parameters, one for each column. If all the parameters are present for the columns then it will return a fourth column. If, however, any one of the three parameters is not found in the table, then it should return a message informing the user which of the parameters is incorrect.
I have tried the following:
SELECT RESULTS, "[status]" =
case
when CostCenterNo <> '800' then 'CentreNotFound'
when EmpNo <> '2' then 'EmpNotFound'
when Surname <> 'sonny' then 'SurnameNotFound'
else null
end
from CostCentres
where
CostCenterNo =
case CostCenterno when
'800' then '800'
else ''
end
and
EmpNo =
case EmpNo when
'2' then '2'
else ''
end
and
Surname =
case Surname when
'sonny' then 'sonny'
else ''
end
this retrieves the correct information when all parameters are correct but then I need for it to say CentreNotFound, EmpNotFound, SurnameNotFound for when the respective parameter is not found in the table.
I have tried looking up the links below but still no luck.
IF statement in SQL Server where clause
Using EXISTS as a column in TSQL
SQL: IF clause within WHERE clause
I have also tried the following code:
select results =
case when CostCenterNo = '800' then
case when EmpNo = '2' then
case when Surname = 'sonny' then
(select results from bcse
where CostCenterNo = 'BW800'
and EmpNo like '2'
and Surname = 'sonny')
else 'surname not found' end
else 'Emp not found' end
else 'center no not found' end
from CostCentres
where (CostCenterno = 'bw800' or CostCenterNo = '%')
and (EmpNo = '2' or EmpNo = '%' )
and (surname = 'sonny' or surname = '%')
The above works for the correct parameters but then again I need it to return the CentreNotFound, EmpNotFound, SurnameNotFound for when the respective parameter is not found in the table.
The WHERE condition should be
where (CostCenterno = 'bw800' or CostCenterNo = '%')
and (EmpNo = '2' or EmpNo like '%' )
and (surname = 'sonny' or surname like '%')
Also if you use parameters, it should be
where (CostCenterno = #CostCenterno or #CostCenterNo = '')
and (EmpNo = #EmpNo or #EmpNo ='' )
and (surname = #surname or #surname ='')
EDIT: You may need to use something like below
declare #error varchar(100)
set #error=
case
when not exists(select * from CostCentres where CostCenterno = #CostCenterno) then
'CenterNotFound'
when not exists(select * from CostCentres where EmpNo = #EmpNo) then
'EmpnoNotFound'
when not exists(select * from CostCentres where surname = #surname) then
'surnameNotFound'
end
select CostCenterno, EmpNo,surname , #error as status
from CostCentres
where
CostCenterno = #CostCenterno
and EmpNo = #EmpNo
and surname = #surname

How to use CASE WHEN in determining special characters?

I'm trying to create a code that will do different update to a specific column based on a set of critierias.
I have a FirstName in the Customer records. Now I need to update the FirstName depending on the data I have in my title.
The logic should go like this...
UPDATE Customer
SET FirstName = If TITLE contains special characters
THEN set firstname to blank
ELSE
SET it to FirstName
From Customer c
INNER JOIN CustomerList cl
on c.customerid = cl.customerid
I'm having troubles doing the logic for the special characters.
I'm not sure whether to use a CASE within a CASE or an IF and CASE statement.
I am able to identify special characters using this code:
SELECT title FROM Customer where LTRIM(RTRIM(title)) NOT LIKE '%[`'' -''|-~.,-#!#$^&*()<>:;''"_+\/=?0-9]%'
I tried to incorporate this into my CASE but I'm getting a syntax error.
Any suggestions on the best way to solve this?
So far my code is like this...
SELECT ID, CASE LTRIM(RTRIM(title))
WHEN Title NOT LIKE '%[`'' -''|-~.,-#!#$^&*()<>:;''"_+\/=?0-9]%' AND RTRIM(LTRIM(title)) NOT IN ('MR', 'MS', 'MRS', 'Miss', 'MSTR', 'MR.', 'MS.', 'MRS.', 'CHD', 'CHIL', 'CHLD', 'DR', 'DR.', 'MAST',''))
THEN title
END
FROM customer
Possible this be helpful for you -
SELECT ID,
CASE
WHEN LTRIM(RTRIM(title)) NOT LIKE '%[`'' -''|-~.,-#!#$^&*()<>:;''"_+\/=?0-9]%'
AND RTRIM(LTRIM(title)) NOT IN ('MR', 'MS', 'MRS', 'Miss', 'MSTR', 'MR.', 'MS.', 'MRS.', 'CHD', 'CHIL', 'CHLD', 'DR', 'DR.', 'MAST','')
THEN title
END
FROM customer
Update:
DECLARE #temp TABLE (title NVARCHAR(50))
INSERT INTO #temp (title)
VALUES ('~test1'), ('MR test'), ('is ok')
SELECT t.*
FROM #temp t
WHERE NOT EXISTS(
SELECT 1
FROM (VALUES
('MR'), ('MS'), ('MRS'),
('Miss'), ('MSTR'), ('MR.'),
('MS.'), ('MRS.'), ('CHD'),
('CHIL'), ('CHLD'), ('DR'),
('DR.'), ('MAST')
) c(t2)
WHERE LTRIM(RTRIM(title)) LIKE '%' + t2 + '%'
)
AND LTRIM(RTRIM(title)) NOT LIKE '%[`'' -''|-~.,-#!#$^&*()<>:;''"_+\/=?0-9]%'
Assuming any character that is not a space or a letter is considered special
UPDATE c
SET FirstName =
case when replace(Title, ' ', '') like '%[^a-z]%'
THEN ''
ELSE FirstName
end
FROM Customer c
INNER JOIN CustomerList cl
on c.customerid = cl.customerid

Using CASE to Return a String If No Results From SELECT Statement

Is it possible to use CASE to return a certain string if there are no results from my SELECT statement?
Example:
DECLARE #accountnumber AS VARCHAR(10)
SET #accountnumber = 'account number to search'
SELECT
CASE
WHEN account IS NOT NULL
THEN 'We Have Records of this Customer'
WHEN account IS NULL
THEN 'We Do Not Have Records For This Customer'
END AS 'result'
FROM call_records
WHERE account = #accountnumber
GROUP BY account
The above does not work since if the account number I am searching for isn't present in my logs table then there would be no results and the message 'We Do Not Have Records For This Customer' would never materialize.
I can do what I am trying to achieve using pure T-SQL with a PRINT command, but I am working with a 3rd party app and the results must be in table form (so SELECT statements only).
You can use EXISTS:
SELECT
CASE
WHEN EXISTS(
SELECT 1 FROM call_records
WHERE account = #accountnumber
)
THEN 'We Have Records of this Customer'
ELSE 'We Do Not Have Records For This Customer'
END AS 'result';
Try:
DECLARE #accountnumber AS VARCHAR(10)
SET #accountnumber = 'account number to search'
SELECT
CASE
WHEN account IS NOT NULL
THEN 'We Have Records of this Customer'
WHEN account IS NULL
THEN 'We Do Not Have Records For This Customer'
END AS 'result'
FROM (select 1 dummy) dummy
left join call_records ON account = #accountnumber
GROUP BY account

How do I check if a SQL Server text column is empty?

I am using SQL Server 2005. I have a table with a text column and I have many rows in the table where the value of this column is not null, but it is empty. Trying to compare against '' yields this response:
The data types text and varchar are incompatible in the not equal to operator.
Is there a special function to determine whether the value of a text column is not null but empty?
where datalength(mytextfield)=0
ISNULL(
case textcolum1
WHEN '' THEN NULL
ELSE textcolum1
END
,textcolum2) textcolum1
Actually, you just have to use the LIKE operator.
SELECT * FROM mytable WHERE mytextfield LIKE ''
To get only empty values (and not null values):
SELECT * FROM myTable WHERE myColumn = ''
To get both null and empty values:
SELECT * FROM myTable WHERE myColumn IS NULL OR myColumn = ''
To get only null values:
SELECT * FROM myTable WHERE myColumn IS NULL
To get values other than null and empty:
SELECT * FROM myTable WHERE myColumn <> ''
And remember use LIKE phrases only when necessary because they will degrade performance compared to other types of searches.
SELECT * FROM TABLE
WHERE ISNULL(FIELD, '')=''
Use the IS NULL operator:
Select * from tb_Employee where ename is null
I know this post is ancient but, I found it useful.
It didn't resolve my issue of returning the record with a non empty text field so I thought I would add my solution.
This is the where clause that worked for me.
WHERE xyz LIKE CAST('% %' as text)
Use DATALENGTH method, for example:
SELECT length = DATALENGTH(myField)
FROM myTABLE
Instead of using isnull use a case, because of performance it is better the case.
case when campo is null then '' else campo end
In your issue you need to do this:
case when campo is null then '' else
case when len(campo) = 0 then '' else campo en
end
Code like this:
create table #tabla(
id int,
campo varchar(10)
)
insert into #tabla
values(1,null)
insert into #tabla
values(2,'')
insert into #tabla
values(3,null)
insert into #tabla
values(4,'dato4')
insert into #tabla
values(5,'dato5')
select id, case when campo is null then 'DATA NULL' else
case when len(campo) = 0 then 'DATA EMPTY' else campo end
end
from #tabla
drop table #tabla
I would test against SUBSTRING(textColumn, 0, 1)
Are null and an empty string equivalent? If they are, I would include logic in my application (or maybe a trigger if the app is "out-of-the-box"?) to force the field to be either null or '', but not the other. If you went with '', then you could set the column to NOT NULL as well. Just a data-cleanliness thing.
I wanted to have a predefined text("No Labs Available") to be displayed if the value was null or empty and my friend helped me with this:
StrengthInfo = CASE WHEN ((SELECT COUNT(UnitsOrdered) FROM [Data_Sub_orders].[dbo].[Snappy_Orders_Sub] WHERE IdPatient = #PatientId and IdDrugService = 226)> 0)
THEN cast((S.UnitsOrdered) as varchar(50))
ELSE 'No Labs Available'
END
You have to do both:
SELECT * FROM Table WHERE Text IS NULL or Text LIKE ''
I know there are plenty answers with alternatives to this problem, but I just would like to put together what I found as the best solution by #Eric Z Beard & #Tim Cooper with #Enrique Garcia & #Uli Köhler.
If needed to deal with the fact that space-only could be the same as empty in your use-case scenario, because the query below will return 1, not 0.
SELECT datalength(' ')
Therefore, I would go for something like:
SELECT datalength(RTRIM(LTRIM(ISNULL([TextColumn], ''))))
try this:
select * from mytable where convert(varchar, mycolumn) = ''
i hope help u!
DECLARE #temp as nvarchar(20)
SET #temp = NULL
--SET #temp = ''
--SET #temp = 'Test'
SELECT IIF(ISNULL(#temp,'')='','[Empty]',#temp)
It will do two things:
Null check and string null check
Replace empty value to default value eg NA.
SELECT coalesce(NULLIF(column_name,''),'NA') as 'desired_name') from table;

Resources