How to use Case statement in SQL correctly - sql

The below Select statement does NOT return a record for me:
Select 1:
SELECT
Case When rcdr.PolicyNumber like '' + bmpd.PaymentReferenceNumber + '%'
Then 'Adc' else 'Exceed' end as System
FROM RcDetailRecords rcdr
join Bil_ManualPaymentDetails bmpd
on rcdr.PolicyNumber like '' + bmpd.PaymentReferenceNumber + '%' + ''
Output:
System =
The below Select statement DOES return a record for me:
Select 2:
SELECT
Case When rcdr.PolicyNumber like '1234567890%'
Then 'Adc' else 'Exceed' end as System
FROM RcDetailRecords rcdr
join BilManualPaymentDetails bmpd
on rcdr.PolicyNumber like '1234567890%'
Output:
System = Adc
Am I missing a tick '' mark somewhere in the first Select ?
BilManualPaymentDetails Table:
PaymentReferenceNumber
123456789020161013025120
RcDetailRecords Table:
PolicyNumber
1234567890

1234567890 is not like 123456789020161013025120%, but 123456789020161013025120 is like 1234567890%
So it appears you have the fields switched, try:
SELECT
CASE WHEN bmpd.PaymentReferenceNumber LIKE '' + rcdr.PolicyNumber + '%'
THEN 'Adc'
ELSE 'Exceed'
END as System
FROM RcDetailRecords rcdr
JOIN Bil_ManualPaymentDetails bmpd
ON bmpd.PaymentReferenceNumber like '' + rcdr.PolicyNumber + '%' + ''

Related

some weird signs appearing on SQL SERVER Query output

i have written a SELECT Query on SQL SERVER 2014 . I have got the desired output . but an apostrophe symbol(') appearing on 'TaskAction' field data(at the end of each data). here it is my script:
SELECT
WOtask.PK,
WOPK,
TaskNo,
TaskAction =
CASE
WHEN WOTask.AssetPK IS NOT NULL THEN '<b>' + Asset.AssetName + ' [' + Asset.AssetID + ']</b> ' + CASE
WHEN Asset.Vicinity IS NOT NULL AND
Asset.Vicinity <> '''' THEN RTRIM(Asset.Vicinity) + ': '
ELSE ''''
END + WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' (Range: '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + '' - '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + )'
ELSE ''''
END
ELSE WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' (Range: '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + '' - '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + )'
ELSE ''''
END
END,
Rate,
Measurement,
Initials,
Fail,
Complete,
Header,
LineStyle,
WOtask.Comments,
WOtask.NotApplicable,
WOTask.Photo1,
WOTask.Photo2
FROM WOtask WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK)
ON Asset.AssetPK = WOTask.AssetPK
LEFT OUTER JOIN AssetSpecification
ON AssetSpecification.PK = WOTask.AssetSpecificationPK
WHERE (WOPK IN (SELECT
WOPK
FROM WO WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK)
ON Asset.AssetPK = WO.AssetPK
LEFT OUTER JOIN AssetHierarchy WITH (NOLOCK)
ON AssetHierarchy.AssetPK = WO.AssetPK
WHERE WO.WOPK = 10109)
)
ORDER BY WOPK, TaskNo
now please check my output and error
please help to solve this issue. Thanks in Advance.
As noted in comments, use ELSE '' instead of ELSE ''''. The reason is that within a pair of single quotes, then '' tells SQL to escape a single quote into your output.
For instance, to show the output User's, you would need SELECT 'User''s'.

error converting % to datatype int in sql

iam using simple query i want year to get extracted and that should be used in table extraction
select *
from v_AuthListInfo LI
where title like '%SUG%'
and Title like '%P1%'
and Title like '%' + '' + year(getdate()) + '' + '%'
I am getting this error
Msg 245, Level 16, State 1, Line 26
Conversion failed when converting the varchar value '%' to data type int.
Ideally it should come 2018 and it should extract those records with 2018
and I want records minus 1 yr means 2017
so in all I want records of 2018 and 2017
but iam not able to get can you tell me where iam going wrong in concatenation
want to combine output of these two queries
select
count(*) [Total Clients], li.title,li.CI_UniqueID,coll.name,
SUM (CASE WHEN ucs.status=3 or ucs.status=1 then 1 ELSE 0 END ) as 'Installed / Not Applicable',
sum( case When ucs.status=2 Then 1 ELSE 0 END ) as 'Required',
sum( case When ucs.status=0 Then 1 ELSE 0 END ) as 'Unknown',
round((CAST(SUM (CASE WHEN ucs.status=3 or ucs.status=1 THEN 1 ELSE 0 END) as float)/count(*) )*100,2) as 'Compliant%',
round((CAST(count(case when ucs.status not in('3','1') THEN '*' end) as float)/count(*))*100,2) as 'NotCompliant%'
From v_Update_ComplianceStatusAll UCS
inner join v_r_system sys on ucs.resourceid=sys.resourceid
inner join v_FullCollectionMembership fcm on ucs.resourceid=fcm.resourceid
inner join v_collection coll on coll.collectionid=fcm.collectionid
inner join v_AuthListInfo LI on ucs.ci_id=li.ci_id
where coll.CollectionID='SMS00001' and
--title like '%SUG%'
Title like '%P1%'
and Title like '%SUG_' + '' + CAST(year(getdate()) as varchar) + '' + '%'
--and Title like '%SUG_' + '' + CAST(year(getdate())-1 as varchar) + '' + '%'
group by li.title,li.CI_UniqueID,coll.name
order by li.title ASC
select
count(*) [Total Clients], li.title,li.CI_UniqueID,coll.name,
SUM (CASE WHEN ucs.status=3 or ucs.status=1 then 1 ELSE 0 END ) as 'Installed / Not Applicable',
sum( case When ucs.status=2 Then 1 ELSE 0 END ) as 'Required',
sum( case When ucs.status=0 Then 1 ELSE 0 END ) as 'Unknown',
round((CAST(SUM (CASE WHEN ucs.status=3 or ucs.status=1 THEN 1 ELSE 0 END) as float)/count(*) )*100,2) as 'Compliant%',
round((CAST(count(case when ucs.status not in('3','1') THEN '*' end) as float)/count(*))*100,2) as 'NotCompliant%'
From v_Update_ComplianceStatusAll UCS
inner join v_r_system sys on ucs.resourceid=sys.resourceid
inner join v_FullCollectionMembership fcm on ucs.resourceid=fcm.resourceid
inner join v_collection coll on coll.collectionid=fcm.collectionid
inner join v_AuthListInfo LI on ucs.ci_id=li.ci_id
where coll.CollectionID='SMS00001' and
--title like '%SUG%'
Title like '%P1%'
-- Title like '%SUG_' + '' + CAST(year(getdate()) as varchar) + '' + '%'
and Title like '%SUG_' + '' + CAST(year(getdate())-1 as varchar) + '' + '%'
group by li.title,li.CI_UniqueID,coll.name
order by li.title ASC
Cast your year to varchar because year returns int value
select * from v_AuthListInfo LI
where title like '%SUG%'
and Title like '%P1%'
and Title like '%' + '' + CAST(year(getdate()) as varchar(4)) + '' + '%'
The problem is that year() returns a number, not a string. Because of this, SQL Server interprets the + as addition, rather than string concatenation.
SQL Server has a convenient function, datename(), that returns a string:
select *
from v_AuthListInfo LI
where title like '%SUG%' and
title like '%P1%' and
title like '%' + datename(year, getdate()) + '%';
The empty strings that you are concatenating in the like pattern are useless.

Adding a WHERE statement to an SQL query based on an IF statement

Issue: I only want to filter the PropertySearch value if there is one
I want to be able to have a dynamic SQL statement based on this.
I have added If #PropertySearch which filters from a textbox on the webform.
The search works up to -- If #PropertySearch <> '' -- and will work if I comment the code
--
If #PropertySearch <> ''
BEGIN
TblA.PropertyID LIKE '%' + #PropertySearch + '%' OR TblA.Propertyname LIKE '%' + #PropertySearch +' %'
END
--
I want to only filter the PropertyID/PropertySearch when there is a #PropertySearch.
I have looked at having 'AND' after 'BEGIN' as well as Nested tables but am struggling
If #RegionID = 1 --then -- Head office users
BEGIN
SELECT TblA.PropertyID as PId, TblA.Propertyname as PNa, TblB.FireSafetyDisplay as FireSafety1, TblB.SlipsandTripsDisplay as SaT
FROM TbPropertyDetails as TblA inner join TbPropertyDetailsSafeguarding as TblB on TblA.PropertyID = TblB.PropertyID
WHERE TblA.RegionID > 0
If #PropertySearch <> ''
BEGIN
TblA.PropertyID LIKE '%' + #PropertySearch + '%' OR TblA.Propertyname LIKE '%' + #PropertySearch +' %'
END
END
WHERE TblA.RegionID > 0 AND (#PropertySearch = ''
OR TblA.PropertyID LIKE '%' + #PropertySearch + '%' OR TblA.Propertyname LIKE '%' + #PropertySearch +' %')

MS sql combine columns in select

I am trying to combine multiple columns (varchar, but used to store boolean 'Y' or '') into a single column (list) with human readable text.
The Table layout is like this:
MEMBER_ID (int) | PROC (varchar) | 50K_12_MTHS (varchar) | 100K_12_MTHS (varchar)
1||||
2|Y|Y||
3|Y|Y|Y|
4|Y|||
For the output of the able sample I am trying to get:
1|
2|Proc, 50
3|Proc, 50, 100
4|Proc
I think the way to do this is with a Case (see below) but can't get it to work.
SELECT
MEMBER_ID,
Gorup =
Select(
CASE PROC
WHEN 'Y'
THEN 'Proc'
END + ', ' +
CASE 50K_12_MTHS
WHEN 'Y'
THEN '50K'
END-- + ', ' +
CASE 100K_12_MTHS
WHEN 'Y'
THEN '100K'
END + ', ' +)
from Members
Nearly...!
SELECT
MEMBER_ID,
CASE [PROC]
WHEN 'Y' THEN 'Proc, '
ELSE ''
END +
CASE [50K_12_MTHS]
WHEN 'Y' THEN '50K,'
ELSE ''
END +
CASE [100K_12_MTH]
WHEN 'Y' THEN '100K, '
ELSE ''
END as [group]
from Members
Try this
SELECT
MEMBER_ID,
(CASE [PROC] WHEN 'Y'
THEN 'Proc' ELSE ''
END +
CASE [50K_12_MTHS] WHEN 'Y'
THEN ', 50K' ELSE '' END
+ CASE [100K_12_MTHS] WHEN 'Y'
THEN ', 100K' ELSE ''
END) as [GROUP]
from Members

T-SQL: CASE statement in WHERE?

I have the following WHERE clause in my SQL query currently:
WHERE c.Town LIKE '%' + #Town + '%'
What I want do is make the first '%' optional - so if the user has selected to just filter by records that just start with the given text, the WHERE would be
WHERE c.Town LIKE #Town + '%'
I assumed the simplest way to do this would be CASE statements, but I'm having no joy as it seems the syntax is incorrect. Can I get any pointers? Here's the CASE statement I was trying:
WHERE c.Town LIKE (CASE WHEN #FilterOptions = 1 THEN '%' ELSE '') + #Town + '%'
You missed the END:
WHERE c.Town LIKE (CASE WHEN #FilterOptions = 1 THEN '%' ELSE '' END) + #Town + '%'
A CASE must end with an END. Try
WHERE c.Town LIKE (CASE WHEN #FilterOptions = 1 THEN '%' ELSE '' END) + #Town + '%'
Case should have end.
I think the below statement can help you.
WHERE c.Town LIKE (CASE WHEN #FilterOptions = 1 THEN '%' ELSE '' END) + #Town + '%