Case with Like operator - sql

Got stuck at using CASE statement with LIKE operator. In the below stored procedure all the parameters are not mandatory so when User doesn't enter PatientName for searching then the below query doesn't return expected results as the LIKE operator is outside which is obvious. I'm looking for something like this so that when User doesn't enter PatientName it will be
(c.LastName + c.Firstname) = #PatientNAme else
(c.LastName + c.Firstname) like '%' + #PatientNAme + '%'
*
(c.LastName + c.Firstname) (
CASE #PatientName
WHEN '' THEN #PatientName = (c.LastName + c.Firstname)
ELSE like '%' + #PatientName + '%'
END
)
*
CREATE proc [dbo].[SearchParkPrescriptionDetails]
#DispenseID INT,
#ParkPrescriptionReasonId INT,
#PrescriptionParkType VARCHAR(50),
#PatientName VARCHAR(120),
#User VARCHAR(120),
#fromdate DATETIME,
#todate DATETIME,
#DateWiseSearch VARCHAR(3),
#PatientID INT
AS
BEGIN
SELECT
a.ParkPrescriptionId
, a.DispenseID
, a.ParkPrescriptionReasonId
, a.ParkDate
, (c.LastName + ' ' + c.Firstname) AS PatientName
, d.PrescriptionType
, e.ParkPrescriptionReason
, a.Notes
, b.ItemCount AS TotalItems
, g.ExemptionReason
,a.[User]
FROM
ParkPrescriptionDetails a
INNER JOIN
Dis_DispenseMaster b
ON
a.DispenseID=b.DispenseID
INNER JOIN
Patient c
ON
b.PatientId = c.PatientId
INNER JOIN
Lookup_PrescriptionType d
ON
b.PrescriptionTypeId = d.PrescriptionTypeId
INNER JOIN
Lookup_ParkPrescriptionReason e
ON
a.ParkPrescriptionReasonId = e.ParkPrescriptionReasonId
LEFT JOIN
Lookup_ExemptionReason g
ON
b.ExemptionReasonId = g.ExemptionReasonId
WHERE
CONVERT(DATE, a.ParkDate) BETWEEN #fromdate AND #todate
AND a.RecallStatus = 'N'
AND a.DispenseID = ( CASE #DispenseID WHEN 0 THEN a.DispenseID ELSE #DispenseID END )
AND b.PatientId = ( CASE #PatientID WHEN 0 THEN b.PatientId ELSE #PatientID END )
AND a.ParkPrescriptionReasonId = ( CASE #ParkPrescriptionReasonId WHEN 0 THEN a.ParkPrescriptionReasonId ELSE #ParkPrescriptionReasonId END )
AND
(
c.LastName + c.Firstname
) LIKE ( CASE #PatientName WHEN '' THEN (c.LastName + c.Firstname) ELSE '%' + #PatientName + '%' END )
AND a.[User] LIKE ( CASE #User WHEN '' THEN a.[User] ELSE '%' + #User + '%' END )
AND b.ParkPrescription = ( CASE #PrescriptionParkType WHEN '' THEN b.ParkPrescription WHEN 'Park' THEN 'Y' END )
AND b.RecallPrescription = ( CASE #PrescriptionParkType WHEN '' THEN b.RecallPrescription WHEN 'Recall' THEN 'Y' END )
AND a.IsDeleted =0
END
========== Changed it Like this. Is this perfect ===========
(c.LastName + ' ' + c.Firstname) = (
CASE #PatientName
WHEN '' THEN (c.LastName + ' ' + c.Firstname)
ELSE '%' + #PatientName + '%'
END
)

Do not use CASE WHEN in where clause. Use OR
(
#PatientName = '' OR
(c.LastName + c.Firstname) LIKE '%' + #PatientName + '%'
) AND
(
#User = '' OR
a.[User] LIKE '%' + #User + '%'
) -- Same for others
instead of
(c.LastName + ' ' + c.Firstname) = (
CASE #PatientName
WHEN '' THEN (c.LastName + ' ' + c.Firstname)
ELSE '%' + #PatientName + '%'
END
)

T-SQL has two forms of CASE. You are using "Simple Case". Try "Searched Case" - e.g.:
CASE
WHEN #PatientName = '' THEN [ return something ]
WHEN #PatientName like [ pattern ] THEN [ return something ]
ELSE [ return something else ]
END

Related

SQL converting CSV text to Table

I have a table with a list of customer orders (s84_Schedule). I have a second table with comments on the orders (s84_ScheduleNotes). When I pull the list of orders from s84_Schedule, I do a left outer join to get the latest comment from s84_ScheduleNotes, because there are not always comments on every order.
Problem: I also have a SQL function that converts a comma-separated list of ProductIDs into a temporary table; this function does not seem to be working properly. I do not understand how these are related, but... If I use only one Product ID (meaning, no comma in the ProductVal variable), the left outer join never pulls in the latest comment from s84_ScheduleNotes. However, if I provide 2 ProductIDs separated by commas in ProductVal, the latest comment will show up.
Here is the code that converts the CSV to a temp table (stole this off the internet somewhere a long time ago)...
CREATE FUNCTION [dbo].[CSVToTable] (#InStr VARCHAR(MAX))
RETURNS #TempTab TABLE
(id int not null)
AS
BEGIN
;-- Ensure input ends with comma
SET #InStr = REPLACE(#InStr + ',', ',,', ',')
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', #INSTR ) <> 0
BEGIN
SELECT #SP = PATINDEX('%,%',#INSTR)
SELECT #VALUE = LEFT(#INSTR , #SP - 1)
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '')
INSERT INTO #TempTab(id) VALUES (#VALUE)
END
RETURN
END
GO
Here is my procedure which pulls the orders and the comments...
CREATE PROCEDURE dbo.GetFilteredSchedule
(
#InstallDateOperator INT,
#InstallDateRange1 DATETIME,
#InstallDateRange2 DATETIME,
#InstallDateDynRange1 INT,
#InstallDateDynRange2 INT,
#CustExpectedOperator INT,
#CustExpectedRange1 DATETIME,
#CustExpectedRange2 DATETIME,
#CustExpectedDynRange1 INT,
#CustExpectedDynRange2 INT,
#CompletedDateOperator INT,
#CompletedDateRange1 DATETIME,
#CompletedDateRange2 DATETIME,
#CompletedDateDynRange1 INT,
#CompletedDateDynRange2 INT,
#ProdInStoreDateOperator INT,
#ProdInStoreDateRange1 DATETIME,
#ProdInStoreDateRange2 DATETIME,
#ProdInStoreDateDynRange1 INT,
#ProdInStoreDateDynRange2 INT,
#InvoiceNumVal VARCHAR(2000),
#InstallerVal VARCHAR(2000),
#CustomerVal VARCHAR(2000),
#SubdivisionVal VARCHAR(2000),
#ProductVal VARCHAR(2000),
#LotNumVal VARCHAR(2000),
#EstimateNumVal VARCHAR(2000),
#SONumVal VARCHAR(2000),
#ProdInStoreVal BIT,
#OrderProcessedVal BIT,
#StatusVal VARCHAR(2000),
#FieldRepVal VARCHAR(2000),
#WorkOrderNumVal VARCHAR(2000),
#WindowVal VARCHAR(2000),
#StoreVal VARCHAR(2000),
#DriverVal VARCHAR(2000),
#YardEmployeeVal VARCHAR(2000),
#TruckTypeVal VARCHAR(2000),
#LotNumExact INT,
#StatusIDExact INT,
#SearchText VARCHAR(2000),
#CustomerIdRestriction VARCHAR(2000),
#OrderBy1 INT,
#OrderBy2 INT
)
AS
BEGIN
SELECT sch.ScheduleID, sch.InstallDate, sch.CustomerExpectedDate, sch.CompletedDate, sch.InvoiceNumber,
sch.InstallerID, sch.CustomerID, sch.SubdivisionID, sch.ProductID, sch.LotNumber, sch.EstimateNumber, sch.SONumber,
sch.ProductInStore, sch.ProductInStoreDate, sch.OrderProcessed, sch.HomeownerInfo, sch.StatusID, sch.FieldRepID,
sch.WindowID, sch.StoreID, sch.ConnectedToProject, sch.DriverEmailAddress, sch.YardEmployeeEmailAddress, sch.TruckTypeID,
installer.InstallerName AS 'InstallerName',
customer.CustomerName AS 'CustomerName',
subdivision.SubdivisionName AS 'SubdivisionName',
product.ProductName AS 'ProductName',
fieldRep.FieldRepName AS 'FieldRepName',
window.WindowName AS 'WindowName',
store.StoreName AS 'StoreName',
stat.StatusName AS 'StatusName',
driver.LastName AS 'DriverLastName', driver.FirstName AS 'DriverFirstName',
yardEmployee.LastName AS 'YardEmployeeLastName', yardEmployee.FirstName AS 'YardEmployeeFirstName',
truckType.TruckTypeName AS 'TruckTypeName',
sch.ScheduleID AS id,
Cast(customer.CustomerName AS VARCHAR(2000)) + ' - ' + Cast(sch.LotNumber AS VARCHAR(2000)) + ' - ' + Cast(subdivision.SubdivisionName AS VARCHAR(2000)) + ' - ' + Cast(product.ProductName AS VARCHAR(2000)) AS 'title',
CONVERT(VARCHAR(50), sch.CustomerExpectedDate, 101) + ' ' + CONVERT(VARCHAR, DATEPART(hh, sch.CustomerExpectedDate)) + ':' + RIGHT('0' + CONVERT(VARCHAR, DATEPART(mi, sch.CustomerExpectedDate)), 2) AS 'start',
CONVERT(VARCHAR(50), DATEADD(hh, 1, sch.CustomerExpectedDate), 101) AS 'end',
stat.StatusColor AS 'backgroundColor',
note.NoteText AS 'NoteText'
FROM s84_Schedule sch
LEFT OUTER JOIN dbo.s84_ScheduleNotes AS note ON note.ScheduleID = (SELECT MAX(n.ScheduleNoteID) FROM dbo.s84_ScheduleNotes n WHERE n.ScheduleID = sch.ScheduleID)
JOIN dbo.s84_Installer AS installer ON sch.InstallerID = installer.InstallerID
JOIN dbo.s84_Customer AS customer on sch.CustomerID = customer.CustomerID
JOIN dbo.s84_Subdivision AS subdivision ON sch.SubdivisionID = subdivision.SubdivisionID
JOIN dbo.s84_Product AS product ON sch.ProductID = product.ProductID
JOIN dbo.s84_FieldRep AS fieldRep ON sch.FieldRepID = fieldRep.FieldRepID
JOIN dbo.s84_Window AS window ON sch.WindowID = window.WindowID
JOIN dbo.s84_Store AS store ON sch.StoreID = store.StoreID
JOIN dbo.s84_Status AS stat ON sch.StatusID = stat.StatusID
JOIN dbo.s84_TruckType AS truckType ON sch.TruckTypeID = truckType.TruckTypeID
LEFT OUTER JOIN dbo.s84_Employee AS driver ON ((#DriverVal IS NOT NULL) AND (driver.EmailAddress = #DriverVal))
LEFT OUTER JOIN dbo.s84_Employee AS yardEmployee ON ((#YardEmployeeVal IS NOT NULL) AND (yardEmployee.EmailAddress = #YardEmployeeVal))
WHERE
(#InvoiceNumVal IS NULL OR (sch.InvoiceNumber LIKE '%' + #InvoiceNumVal + '%')) AND
(#InstallerVal IS NULL OR (installer.InstallerID = #InstallerVal)) AND
(#CustomerVal IS NULL OR (customer.CustomerName LIKE '%' + #CustomerVal + '%')) AND
(#SubdivisionVal IS NULL OR (subdivision.SubdivisionName LIKE '%' + #SubdivisionVal + '%')) AND
(#ProductVal IS NULL OR ( sch.ProductID IN (SELECT * FROM dbo.CSVToTable(#ProductVal)) )) AND
(#LotNumVal IS NULL OR (sch.LotNumber LIKE '%' + #LotNumVal + '%')) AND
(#EstimateNumVal IS NULL OR (sch.EstimateNumber LIKE '%' + #EstimateNumVal + '%')) AND
(#SONumVal IS NULL OR (sch.SONumber LIKE '%' + #SONumVal + '%')) AND
(#ProdInStoreVal IS NULL OR (sch.ProductInStore = #ProdInStoreVal)) AND
(#OrderProcessedVal IS NULL OR (sch.OrderProcessed = #OrderProcessedVal)) AND
(#FieldRepVal IS NULL OR (fieldRep.FieldRepID = #FieldRepVal)) AND
(#WorkOrderNumVal IS NULL OR (sch.ScheduleID LIKE '%' + #WorkOrderNumVal + '%')) AND
(#WindowVal IS NULL OR (window.WindowName LIKE '%' + #WindowVal + '%')) AND
(#StoreVal IS NULL OR (store.StoreName LIKE '%' + #StoreVal + '%')) AND
(#DriverVal IS NULL OR ((driver.FirstName LIKE '%' + #DriverVal + '%') OR (driver.LastName LIKE '%' + #DriverVal + '%'))) AND
(#YardEmployeeVal IS NULL OR ((yardEmployee.FirstName LIKE '%' + #YardEmployeeVal + '%') OR (yardEmployee.LastName LIKE '%' + #YardEmployeeVal + '%'))) AND
(#TruckTypeVal IS NULL OR (truckType.TruckTypeName LIKE '%' + #TruckTypeVal + '%')) AND
(#LotNumExact IS NULL OR (sch.LotNumber = #LotNumExact)) AND
(#StatusIDExact IS NULL OR (sch.StatusID = #StatusIDExact)) AND
(#CustomerIdRestriction IS NULL OR ( sch.CustomerID IN (SELECT * FROM dbo.CSVToTable(#CustomerIdRestriction)) )) AND
(#StatusVal IS NULL OR
( sch.StatusID IN (SELECT * FROM dbo.CSVToTable(#StatusVal)) OR
(
('9999' IN (SELECT * FROM dbo.CSVToTable(#StatusVal)) ) AND
( sch.StatusID NOT IN (SELECT * FROM (VALUES ('1'), ('2'), ('3'), ('4')) AS X(id)) )
)
)
) AND
(((#InstallDateOperator IS NULL) OR (#InstallDateOperator = 99)) OR
(#InstallDateOperator = 1 AND sch.InstallDate = #InstallDateRange1) OR
(#InstallDateOperator = 2 AND sch.InstallDate <= #InstallDateRange1) OR
(#InstallDateOperator = 3 AND sch.InstallDate >= #InstallDateRange1) OR
(#InstallDateOperator = 4 AND sch.InstallDate >= #InstallDateRange1 AND sch.InstallDate <= #InstallDateRange2) OR
(#InstallDateOperator = 5 AND sch.InstallDate BETWEEN DATEADD(mm,-#InstallDateDynRange1,GETDATE()) AND DATEADD(mm,#InstallDateDynRange2,GETDATE()))
) AND
(((#CustExpectedOperator IS NULL) OR (#CustExpectedOperator = 99)) OR
(#CustExpectedOperator = 1 AND sch.CustomerExpectedDate = #CustExpectedRange1) OR
(#CustExpectedOperator = 2 AND sch.CustomerExpectedDate <= #CustExpectedRange1) OR
(#CustExpectedOperator = 3 AND sch.CustomerExpectedDate >= #CustExpectedRange1) OR
(#CustExpectedOperator = 4 AND sch.CustomerExpectedDate >= #CustExpectedRange1 AND sch.CustomerExpectedDate <= #CustExpectedRange2) OR
(#CustExpectedOperator = 5 AND sch.CustomerExpectedDate BETWEEN DATEADD(mm,-#CustExpectedDynRange1,GETDATE()) AND DATEADD(mm,#CustExpectedDynRange2,GETDATE()))
) AND
(((#CompletedDateOperator IS NULL) OR (#CompletedDateOperator = 99)) OR
(#CompletedDateOperator = 1 AND sch.CompletedDate = #CompletedDateRange1) OR
(#CompletedDateOperator = 2 AND sch.CompletedDate <= #CompletedDateRange1) OR
(#CompletedDateOperator = 3 AND sch.CompletedDate >= #CompletedDateRange1) OR
(#CompletedDateOperator = 4 AND sch.CompletedDate >= #CompletedDateRange1 AND sch.CompletedDate <= #CompletedDateRange2) OR
(#CompletedDateOperator = 5 AND sch.CompletedDate BETWEEN DATEADD(mm,-#CompletedDateDynRange1,GETDATE()) AND DATEADD(mm,#CompletedDateDynRange2,GETDATE()))
) AND
(((#ProdInStoreDateOperator IS NULL) OR (#ProdInStoreDateOperator = 99)) OR
(#ProdInStoreDateOperator = 1 AND sch.ProductInStoreDate = #ProdInStoreDateRange1) OR
(#ProdInStoreDateOperator = 2 AND sch.ProductInStoreDate <= #ProdInStoreDateRange1) OR
(#ProdInStoreDateOperator = 3 AND sch.ProductInStoreDate >= #ProdInStoreDateRange1) OR
(#ProdInStoreDateOperator = 4 AND sch.ProductInStoreDate >= #ProdInStoreDateRange1 AND sch.ProductInStoreDate <= #ProdInStoreDateRange2) OR
(#ProdInStoreDateOperator = 5 AND sch.ProductInStoreDate BETWEEN DATEADD(mm,-#ProdInStoreDateDynRange1,GETDATE()) AND DATEADD(mm,#ProdInStoreDateDynRange2,GETDATE()))
) AND
((#SearchText IS NULL) OR
( sch.InvoiceNumber LIKE '%' + #SearchText + '%' OR
installer.InstallerName LIKE '%' + #SearchText + '%' OR
customer.CustomerName LIKE '%' + #SearchText + '%' OR
subdivision.SubdivisionName LIKE '%' + #SearchText + '%' OR
product.ProductName LIKE '%' + #SearchText + '%' OR
sch.LotNumber LIKE '%' + #SearchText + '%' OR
sch.EstimateNumber LIKE '%' + #SearchText + '%' OR
sch.SONumber LIKE '%' + #SearchText + '%' OR
stat.StatusName LIKE '%' + #SearchText + '%' OR
fieldRep.FieldRepName LIKE '%' + #SearchText + '%' OR
sch.ScheduleID LIKE '%' + #SearchText + '%' OR
window.WindowName LIKE '%' + #SearchText + '%' OR
store.StoreName LIKE '%' + #SearchText + '%'
))
ORDER BY
CASE #OrderBy2
WHEN 1 THEN sch.InstallDate
WHEN 2 THEN sch.CustomerExpectedDate
WHEN 3 THEN sch.CustomerExpectedDate
WHEN 4 THEN sch.CompletedDate
WHEN 5 THEN sch.InvoiceNumber
WHEN 6 THEN installer.InstallerName
WHEN 7 THEN customer.CustomerName
WHEN 8 THEN subdivision.SubdivisionName
WHEN 9 THEN product.ProductName
WHEN 10 THEN sch.LotNumber
WHEN 11 THEN sch.EstimateNumber
WHEN 12 THEN sch.SONumber
WHEN 13 THEN sch.ProductInStore
WHEN 14 THEN sch.ProductInStoreDate
WHEN 15 THEN sch.OrderProcessed
WHEN 16 THEN stat.StatusName
WHEN 17 THEN fieldRep.FieldRepName
WHEN 18 THEN window.WindowName
WHEN 19 THEN store.StoreName
WHEN 20 THEN driver.LastName
WHEN 21 THEN yardEmployee.LastName
ELSE sch.CustomerExpectedDate
END,
CASE #OrderBy1
WHEN 1 THEN sch.InstallDate
WHEN 2 THEN sch.CustomerExpectedDate
WHEN 3 THEN sch.CustomerExpectedDate
WHEN 4 THEN sch.CompletedDate
WHEN 5 THEN sch.InvoiceNumber
WHEN 6 THEN installer.InstallerName
WHEN 7 THEN customer.CustomerName
WHEN 8 THEN subdivision.SubdivisionName
WHEN 9 THEN product.ProductName
WHEN 10 THEN sch.LotNumber
WHEN 11 THEN sch.EstimateNumber
WHEN 12 THEN sch.SONumber
WHEN 13 THEN sch.ProductInStore
WHEN 14 THEN sch.ProductInStoreDate
WHEN 15 THEN sch.OrderProcessed
WHEN 16 THEN stat.StatusName
WHEN 17 THEN fieldRep.FieldRepName
WHEN 18 THEN window.WindowName
WHEN 19 THEN store.StoreName
WHEN 20 THEN driver.LastName
WHEN 21 THEN yardEmployee.LastName
ELSE sch.CustomerExpectedDate
END;
END;
GO
When I provide values to the dbo.GetFilteredSchedule Procedure, these are the vars I set...
I set ProductVal to "26"
I set StatusVal to "1,3,4,9999"
I set OrderBy1 and OrderBy2 to "3"
Everything else is NULL
Here's a print screen of what my table looks like...
This looks wrong:
LEFT OUTER JOIN dbo.s84_ScheduleNotes AS note
ON note.ScheduleID = (SELECT MAX(n.ScheduleNoteID) FROM dbo.s84_ScheduleNotes n WHERE n.ScheduleID = sch.ScheduleID)
I believe note.ScheduleID should be note.ScheduleNoteID

A constant expression was encountered in the ORDER BY list

Below is my dynamic query and it's not working.
It threw:
A constant expression was encountered in the ORDER BY list, position 2.
Original dynamic query:
SET #QueryVendorName = ';WITH
cteForPriceVen AS (select AI.ItemID, AI.ItemPartNumber as ItemPartNumber, AI.ItemDescription, cteForPrice.VendorPrice as Price, cteForPrice.UpdatedDate as UpdatedDate, cteForPrice.IsLocked as IsLocked
from AerospaceItems (nolock) AI
inner join VendorItemPricing (nolock) cteForPrice
on AI.ItemPartNumber = cteForPrice.ItemPartNumber where cteForPrice.VendorName = ''' + #VendorName + ''' AND
cteForPrice.ObsoleteItem = ''' + cast (#ItemType as char(1)) + ''') select * from cteForPriceVen'
SET #OrderQuery = '
WHERE (''' + cast (#Description as varchar(250)) + ''' = '''' OR cteForPriceVen.ItemDescription like ''%' + cast (#Description as varchar(250)) + '%'')
AND (''' + cast (#PartNumber as varchar(99)) + ''' = '''' OR cteForPriceVen.ItemPartNumber like ''%' + cast (#PartNumber as varchar(99)) + '%'')
AND (''' + cast (#PriceFrom as varchar(25)) + ''' = '''' OR Price >= ''' + cast (#PriceFrom as varchar(99)) + ''')
AND (''' + cast (#PriceTo as varchar(25)) + ''' = '''' OR Price <= ''' + cast (#PriceTo as varchar(99)) + ''')
AND (''' + cast (#DateFrom as varchar(25)) + ''' = '''' OR UpdatedDate >= ''' + cast (#DateFrom as varchar(99)) + ''')
AND (''' + cast (#DateTo as varchar(25)) + ''' = '''' OR UpdatedDate <= ''' + cast (#DateTo as varchar(99)) + ''')
ORDER BY
CASE WHEN '''+ #OrderBy +'''=''ItemDescription'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''0'' THEN cteForPriceVen.ItemDescription END ASC,
CASE WHEN '''+ #OrderBy +'''=''ItemDescription'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''1'' THEN cteForPriceVen.ItemDescription END DESC,
CASE WHEN '''+ #OrderBy +'''=''ItemPartNumber'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''0'' THEN cteForPriceVen.ItemPartNumber END ASC,
CASE WHEN '''+ #OrderBy +'''=''ItemPartNumber'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''1'' THEN cteForPriceVen.ItemPartNumber END DESC,
CASE WHEN '''+ #OrderBy +'''=''Price'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''0'' THEN Price END ASC,
CASE WHEN '''+ #OrderBy +'''=''Price'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''1'' THEN Price END DESC,
CASE WHEN '''+ #OrderBy +'''=''UpdatedDate'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''0'' THEN UpdatedDate END ASC,
CASE WHEN '''+ #OrderBy +'''=''UpdatedDate'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''1'' THEN UpdatedDate END DESC'
Extracted Query:
;WITH
cteForPriceVen AS (select AI.ItemID, AI.ItemPartNumber as ItemPartNumber, AI.ItemDescription, cteForPrice.VendorPrice as Price, cteForPrice.UpdatedDate as UpdatedDate, cteForPrice.IsLocked as IsLocked
from AerospaceItems (nolock) AI
inner join VendorItemPricing (nolock) cteForPrice
on AI.ItemPartNumber = cteForPrice.ItemPartNumber where cteForPrice.VendorName = 'Apple' AND
cteForPrice.ObsoleteItem = '0') select * from cteForPriceVen
WHERE ('' = '' OR cteForPriceVen.ItemDescription like '%%')
AND ('' = '' OR cteForPriceVen.ItemPartNumber like '%%')
AND ('' = '' OR Price >= '')
AND ('' = '' OR Price <= '')
AND ('' = '' OR UpdatedDate >= '')
AND ('' = '' OR UpdatedDate <= '')
ORDER BY
CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '0' THEN cteForPriceVen.ItemDescription END ASC,
CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '1' THEN cteForPriceVen.ItemDescription END DESC
If I remove second order by line, CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '1' THEN cteForPriceVen.ItemDescription END DESC the query seems working.
The second line:
CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '1' THEN cteForPriceVen.ItemDescription END DESC
Is equivalent to NULL. You can't order something by NULL.
edit
If this statement is being generated by a dynamic query, what you need to do is fix the way you build the dynamic query:
#orderQuery = ' ORDER BY '
IF #OrderBy = 'ItemDescription'
BEGIN
orderQuery += ' cteForPriceVen.ItemDescription '
orderQuery += CASE WHEN #OrderMode = 1 THEN 'ASC' ELSE 'DESC' END
END
This line just doesn't make sense:
CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '0'
shouldn't it be something like:
CASE WHEN variableName = 'Value' ...

constraint formulation in inner join

I've the following problem. Take a look at this part of query
inner join tObjClassifier azoc WITH (NOLOCK index=XAK1tDepClassifier)
on azoc.ObjType = 8
and azoc.ParentID = #ObjClassifierID
and azoc.Brief = azfo.Brief
and case
when PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param) is null then azn.NodeType = 2
else PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param)>0
end
here , I'm interested in this part
and case
when PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param) is null then azn.NodeType = 2
else PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param)>0
end
How can I do this part without getting errors. Briefly, If condition PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param)>0
not satisfied, disregard this condition and use this azn.NodeType = 2 condition. Thanks.
we can rearrange above condition as this also:
and case
when ltrim(rtrim(azn.Brief)) = azoc.Param is null then azn.NodeType = 2
else ltrim(rtrim(azn.Brief)) = azoc.Param)
end
PATINDEX returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found. So try use OR condition:
...
and azoc.Brief = azfo.Brief
and
(
(PATINDEX( ('%' + ltrim(rtrim(azn.Brief)) + '%' ) , azoc.Param)>0)
OR
(azn.NodeType = 2)
)

pull SQL results for search criteria conditions

Notice the 2 queries below. The 1st one does a union on 4 queries. I'm trying to write #2 for search conditions based on the 3 SQL variables prefixed with an "#". So rather than doing a union, we have to take all 3 parameters into consideration for the search. And if any parameter/variable is '' (or NULL), just ignore that condition, but still perform the search. But all fields have to combine with each other for a single row/record in the search results.
How do I re-write QUERY #2 so that it pulls results based on the search conditions (#companyName, #primaryPhone and #postalCode)? I think each section in the where clause has to have some OR condition (so it doesn't skip the row for a ''/NULL search condition), but I'm curious how this is typically done. The #primaryPhone part of the where clause is a little trickier because it looks at both phone and fax.
QUERY #1
SELECT tempTable.optionValue, tempTable.optionText FROM (
SELECT
address.addressid AS 'optionValue',
address.name AS 'optionText'
FROM
dbo.address
WHERE
addressid=1
UNION
-- Company Name internal partial match
SELECT
address.addressid AS 'optionValue',
('[' + CAST(address.addressid AS NVARCHAR(10)) + '] ' + ISNULL(address.name,'') + ', ' + ISNULL(address1,'') + ', ' + ISNULL(city,'') + ' ' + ISNULL(statecode,'') + ', ' + ISNULL(countrycode,'') + ' ' + ISNULL(postalcode,'')) AS 'optionText'
FROM
dbo.[address]
LEFT OUTER JOIN dbo.contact_address ON dbo.address.addressid = dbo.contact_address.addressid
LEFT OUTER JOIN dbo.clientcontact ON dbo.contact_address.contactid = dbo.clientcontact.contactid
LEFT OUTER JOIN dbo.client ON dbo.clientcontact.clientid = dbo.client.clientid
LEFT OUTER JOIN dbo.contact ON dbo.contact_address.contactid = dbo.contact.contactid
WHERE
client.name IS NOT NULL
AND client.name != ''
AND #companyName != ''
AND #companyName IS NOT NULL
AND client.name LIKE '%' + #companyName + '%'
AND clientcontact.contacttypeid = 3 --primary contacts only
UNION
-- Primary Phone/Fax internal partial match
SELECT
address.addressid AS 'optionValue',
('[' + CAST(address.addressid AS NVARCHAR(10)) + '] ' + ISNULL(address.name,'') + ', ' + ISNULL(address1,'') + ', ' + ISNULL(city,'') + ' ' + ISNULL(statecode,'') + ', ' + ISNULL(countrycode,'') + ' ' + ISNULL(postalcode,'')) AS 'optionText'
FROM
dbo.[contact]
LEFT OUTER JOIN dbo.clientcontact ON dbo.contact.contactid = dbo.clientcontact.contactid
LEFT OUTER JOIN dbo.contact_address ON dbo.contact.contactid = dbo.contact_address.contactid
LEFT OUTER JOIN dbo.address ON dbo.contact_address.addressid = dbo.address.addressid
WHERE
(
contact.dayphone IS NOT NULL
AND contact.dayphone != ''
AND #primaryPhone != ''
AND #primaryPhone IS NOT NULL
AND contact.dayphone LIKE '%' + #primaryPhone + '%'
)
OR
(
contact.fax IS NOT NULL
AND contact.fax != ''
AND #primaryPhone != ''
AND #primaryPhone IS NOT NULL
AND contact.fax LIKE '%' + #primaryPhone + '%'
)
AND clientcontact.contacttypeid = 3 --primary contacts only
UNION
SELECT
address.addressid AS 'optionValue',
('[' + CAST(address.addressid AS NVARCHAR(10)) + '] ' + ISNULL(address.name,'') + ', ' + ISNULL(address1,'') + ', ' + ISNULL(city,'') + ' ' + ISNULL(statecode,'') + ', ' + ISNULL(countrycode,'') + ' ' + ISNULL(postalcode,'')) AS 'optionText'
FROM
dbo.[contact]
LEFT OUTER JOIN dbo.clientcontact ON dbo.contact.contactid = dbo.clientcontact.contactid
LEFT OUTER JOIN dbo.contact_address ON dbo.contact.contactid = dbo.contact_address.contactid
LEFT OUTER JOIN dbo.address ON dbo.contact_address.addressid = dbo.address.addressid
WHERE
#postalCode != ''
AND #postalCode IS NOT NULL
AND address.postalcode LIKE #postalCode + '%'
AND clientcontact.contacttypeid = 3 --primary contacts only
) AS tempTable
QUERY #2 (SEARCH)
SELECT tempTable.optionValue, tempTable.optionText FROM (
SELECT
address.addressid AS 'optionValue',
address.name AS 'optionText'
FROM
dbo.address
WHERE
addressid=1
UNION
SELECT
address.addressid AS 'optionValue',
('[' + CAST(address.addressid AS NVARCHAR(10)) + '] ' + ISNULL(address.name,'') + ', ' + ISNULL(address1,'') + ', ' + ISNULL(city,'') + ' ' + ISNULL(statecode,'') + ', ' + ISNULL(countrycode,'') + ' ' + ISNULL(postalcode,'')) AS 'optionText'
FROM
dbo.[address]
LEFT OUTER JOIN dbo.contact_address ON dbo.address.addressid = dbo.contact_address.addressid
LEFT OUTER JOIN dbo.clientcontact ON dbo.contact_address.contactid = dbo.clientcontact.contactid
LEFT OUTER JOIN dbo.client ON dbo.clientcontact.clientid = dbo.client.clientid
LEFT OUTER JOIN dbo.contact ON dbo.contact_address.contactid = dbo.contact.contactid
WHERE
(
client.name IS NOT NULL
AND client.name != ''
AND #companyName != ''
AND #companyName IS NOT NULL
AND client.name LIKE '%' + #companyName + '%'
)
AND
(
(
contact.dayphone IS NOT NULL
AND contact.dayphone != ''
AND #primaryPhone != ''
AND #primaryPhone IS NOT NULL
AND contact.dayphone LIKE '%' + #primaryPhone + '%'
)
OR
(
contact.fax IS NOT NULL
AND contact.fax != ''
AND #primaryPhone != ''
AND #primaryPhone IS NOT NULL
AND contact.fax LIKE '%' + #primaryPhone + '%'
)
)
AND
(
#postalCode != ''
AND #postalCode IS NOT NULL
AND address.postalcode LIKE #postalCode + '%'
)
AND clientcontact.contacttypeid = 3 --primary contacts only
) AS tempTable
EDIT New Rules
| Field = '' or NULL | Field != '' or NULL
---------------------+----------------------+-----------------------
Param = '' or NULL | Include Record | Include Record
---------------------+----------------------+-----------------------
Param != '' or NULL | Exclude Record | Include if Match
WHERE
(
#companyName = ''
OR #companyName IS NULL
OR client.name LIKE '%' + #companyName + '%'
)
AND
(
(
#primaryPhone = ''
OR #primaryPhone IS NULL
OR contact.dayphone LIKE '%' + #primaryPhone + '%'
)
OR
(
#primaryPhone = ''
OR #primaryPhone IS NULL
OR contact.fax LIKE '%' + #primaryPhone + '%'
)
)
AND
(
#postalCode = ''
OR #postalCode IS NULL
OR address.postalcode LIKE #postalCode + '%'
)
AND clientcontact.contacttypeid = 3 --primary contacts only
#postalCode != ''
AND #postalCode IS NOT NULL
AND address.postalcode LIKE #postalCode + '%'
could be written as
AND address.postalcode LIKE IsNull(#postalCode, '') + '%'
no need for testing that you have a variable at all, sql will ignore it in the execution when = '%'
a mass of ORs in my experience will really slow down the query (but look at the exe plan anyway). this is a heck of a lot easier on the eye also imo.

SQL Server Conditional Mailing Address Formatting

I have the following SQL to format a US address into each line for a mailing address but it is rather ugly. Is there a better way to solve this problem or does it have to be this ugly? Also, the problem with this code is that it always ends up with an extra new line at the end.
declare #NL varchar(2);
set #NL = char(13) + char(10);
select
case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + #NL else '' end
+ case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + #NL else '' end
+ case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + #NL else '' end
+ case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + #NL else '' end
+ case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + #NL else '' end
+ case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + #NL else '' end
as FormattedMailingAddress
from Address
where Id = 1
If your Sql Server Settings are such that NULL + varchar returns NULL (SET CONCAT_NULL_YIELDS_NULL (Transact-SQL)), this can help.
DECLARE #Address TABLE(
ID INT,
AttentionLine VARCHAR(50),
Recipient VARCHAR(50),
AddlAddrLine VARCHAR(50),
DeliveryAddr VARCHAR(50),
LastLine VARCHAR(50),
Country VARCHAR(50)
)
declare #NL varchar(2);
set #NL = char(13) + char(10);
INSERT INTO #Address SELECT 1, NULL, '1', NULL, '2', NULL, '3'
select
case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + #NL else '' end
+ case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + #NL else '' end
+ case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + #NL else '' end
+ case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + #NL else '' end
+ case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + #NL else '' end
+ case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + #NL else '' end
as FormattedMailingAddress ,
RTRIM(coalesce(AttentionLine + #NL,'')) +
RTRIM(coalesce(Recipient + #NL,'')) +
RTRIM(coalesce(AddlAddrLine + #NL,'')) +
RTRIM(coalesce(DeliveryAddr + #NL,'')) +
RTRIM(coalesce(LastLine + #NL,'')) +
RTRIM(coalesce(Country + #NL,''))
from #Address
where Id = 1
I realize this is an old question, but there is a new solution to this problem: the CONCAT_WS() function, which is new for SQL Server 2017 (it's also available for Azure SQL Database).
SELECT CONCAT_WS (
CHAR(13) + CHAR(10), --Separator
NULLIF(AttentionLine, ''),
NULLIF(Recipient, ''),
NULLIF(AddlAddrLine, ''),
NULLIF(DeliveryAddr, ''),
NULLIF(LastLine, ''),
NULLIF(Country, '')
)
AS FormattedMailingAddress
FROM Address
WHERE Id = 1
NULL values are ignored by the function, which is why NULLIF is used with each argument/parameter in this example. (When the argument/parameter evaluates to NULL, the separator won't be added either). Here's a short blog post with some more details: New For SQL Server 2017: T-SQL Function CONCAT_WS