Optional Conditional statement in where clause - sql-server

I need to add a condition in my WHERE clause that will include items in a search if #UserRoleId = 4, else exclude them from the search (SQL Server).
INSERT INTO #partData
(
PartPrefix,
PartNumber,
MyProDescription,
ItemNumber,
PartType,
Side,
VehicleLocation,
MyProPrice
)
SELECT
CASE
WHEN LEFT(myParts.MyProDescription, 4) = 'FOIL' THEN 'FOIL'
ELSE LEFT(myParts.PartNumber, 3)
END,
PartNumber,
MyProDescription,
ItemNumber,
PartType,
Side,
VehicleLocation,
MyProPrice
FROM
MyProExport myParts
WHERE
#year BETWEEN myParts.YearFrom AND myParts.YearTo AND
myParts.CarMake = #make AND
REPLACE(myParts.CarModel, ' ', '') = REPLACE(#model, ' ', '') AND
(
myParts.EngineDisplacement = #engine OR
myParts.EngineDisplacement = 'ALL'
) AND
LEFT(myParts.PartNumber, 3) NOT IN ('300','400') -- Exclude these parts if not #UserRoleId = 4
The last statement needs to be modified to display 300 and 400 only if #UserRoleId is = 4. Else just show 300. I’m confused on how to set this up. I’ve tried:
CASE
WHEN #UserRoleId = 4 THEN LEFT(myParts.Number, 3) NOT IN ('300','400') -- Exclude parts
with no luck...

Instead of a case statement, just use AND/OR logic.
AND (LEFT(myParts.HollanderNumber, 3) = '300'
OR (#UserRoleID = 4 AND LEFT(myParts.HollanderNumber, 3) = '400'))
This will always display 300 and only display 400 if the #UserRoleID = 4

Related

update multidimensional arrays in postgresql

id Weather
1 {{KS,'S'},{MO,'S'},{CA,'S'}}
I am trying to update 'S' to 'W' for all KS,MO,CA.
I am executing below query and it is throwing me an error
UPDATE table
SET Weather[][2] ='W' where id=1;
expected output
id Weather
1 {{KS,'W'},{MO,'W'},{CA,'W'}}
I think is possible using ordinary UPDATE.
Let's try to select items what we need to replace:
-- first, second and third item from array and convert to string
SELECT array_to_string(weather[1:1], ',') AS KS,
array_to_string(weather[2:2], ',') AS MO,
array_to_string(weather[3:3], ',') AS CA
FROM test_tbl;
Result: "KS,'S'","MO,'S'","CA,'S'"
Now we can select records records for update using just comparing string with array item(as string):
SELECT * FROM test_tbl
-- KS,'S'
WHERE array_to_string(weather[1:1], ',') = concat('KS,', quote_literal('S'))
-- MO,'S'
-- array_to_string(weather[2:2], ',') = concat('MO,', quote_literal('S'))
-- CA,'S'
-- array_to_string(weather[3:3], ',') = concat('CA,', quote_literal('S'))
Ok. Now we need just to merge array by parts with a new item.
UPDATE test_tbl
-- generate first item + other items
SET weather = string_to_array(concat('KS,', quote_literal('W')), ',')::varchar[] || weather[2:]
WHERE array_to_string(weather[1:1], ',') = concat('KS,', quote_literal('S'));
UPDATE test_tbl
-- first item + generate second + other items
SET weather = weather[1:1] || string_to_array(concat('MO,', quote_literal('W')), ',')::varchar[] || weather[3:]
WHERE array_to_string(weather[2:2], ',') = concat('MO,', quote_literal('S'));
UPDATE test_tbl
-- first + second items, generate third + other items
SET weather = weather[0:2] || string_to_array(concat('CA,', quote_literal('W')), ',')::varchar[] || weather[4:]
WHERE array_to_string(weather[3:3], ',') = concat('CA,', quote_literal('S'));
Result: {{KS,'W'},{MO,'W'},{CA,'W'}}. Hope this helps
I believe that normalizing your data would be the best solution, but if it is not an option for you, try this function:
CREATE OR REPLACE FUNCTION change_array(p TEXT[][]) RETURNS TEXT[][] AS $$
DECLARE row record; res TEXT[][];
DECLARE i INT :=0;
BEGIN
LOOP
EXIT WHEN i = array_length(p,1);
i:=i+1;
IF p[i:i][1:2] <# ARRAY[['KS','S']] THEN
res := res || ARRAY[['KS','W']];
ELSEIF p[i:i][1:2] <# ARRAY[['MO','S']] THEN
res := res || ARRAY[['MO','W']];
ELSEIF p[i:i][1:2] <# ARRAY[['CA','S']] THEN
res := res || ARRAY[['CA','W']];
ELSE res := res || p[i:i];
END IF;
END LOOP;
RETURN res;
END;
$$ LANGUAGE plpgsql ;
Testing with your example..
SELECT change_array(ARRAY[['KS','S'],['MO','S'],['CA','S'],['XX','S']]);
change_array
-------------------------------
{{KS,W},{MO,W},{CA,W},{XX,S}}
(1 Zeile)

Msg 102, Level 15, State 1, Procedure SP_Get_ZINTLL, Line 36 Incorrect syntax near ','

I am getting an incorrect syntax error on line 35/36 in the following query:
CREATE PROCEDURE afm.SP_Get_ZINTLL
AS
Begin
SELECT DISTINCT ls_id AS ZINTLSID_0
,'ARC' AS ZINTSRCCODE_0 ,landlord_tenant
,date_start
,coalesce(ls.bl_id, ls.pr_id) as [ZINTLSTYPE_0]
,coalesce(date_end, GETDATE()) as [ZINTSTRDAT_0]
,tn_name
,ld_name
,isnull(purchase_requisition, 0) as [ZINTBPRNUM_0]
,coalesce(ls.asset_id,0) as [ZINTBPSNUM_0]
, ZINTCCE1_0 = ls.ls_id
--init_value defaulting to JHB removed 2018-06-22
SELECT dim_code
FROM afm.za_dim_lookup
WHERE init_value = coalesce(ls.registered_office, '')
AND dim_type = 'DT1'
,ZINTCCE2_0 = ls.ls_id
SELECT dim_code
FROM afm.za_dim_lookup
WHERE init_value = 'DEFAULT_LS'
AND dim_type = 'DT2'
)
end
As a pure guess, the 2 SELECTs are meant to be subqueries, then this is probably what you are after...
SELECT DISTINCT
ls_id AS ZINTLSID_0,
'ARC' AS ZINTSRCCODE_0,
landlord_tenant,
date_start,
COALESCE(ls.bl_id, ls.pr_id) AS [ZINTLSTYPE_0],
COALESCE(date_end, GETDATE()) AS [ZINTSTRDAT_0],
tn_name,
ld_name,
ISNULL(purchase_requisition, 0) AS [ZINTBPRNUM_0],
COALESCE(ls.asset_id, 0) AS [ZINTBPSNUM_0],
ls.ls_id AS ZINTCCE1_0,
--init_value defaulting to JHB removed 2018-06-22
(SELECT dim_code
FROM afm.za_dim_lookup
WHERE init_value = COALESCE(ls.registered_office, '')
AND dim_type = 'DT1'
AND ZINTCCE2_0 = ls.ls_id), --AS ...??? Will this only return 1 row?
(SELECT dim_code
FROM afm.za_dim_lookup
WHERE init_value = 'DEFAULT_LS'
AND dim_type = 'DT2') --AS ...??? Will this only return 1 row?
FROM ...;
This is probably going to generate more errors though (I suspect a sub-query returned more than 1 row error would be one).
You would be far better off providing sample data and expected results, as well as your full query.

How to create drop-down list in SSRS based on WHERE clause below?

At my organization we using UI third party tool that communicates with SQL database. I have access to a database, but not to the tool.
Based on a stored procedure below user able to choose from drop-down list DairyStatus "Open", "Closed", or "Both"
ALTER Procedure
AS
#ShowOpen bit = 0,
#ShowClosed bit = 0
SELECT
FROM
WHERE
AND
(
(CASE WHEN (#ShowOpen = 1) THEN
CASE WHEN (tblNoteRecipients.CompletedDate IS NULL and tblNoteRecipients.IsDiary = 1) or tblNoteRecipients.UserGUID is null THEN 1 ELSE 0 END
ELSE
1
END = 1)
AND
(CASE WHEN (#ShowClosed = 1) THEN
CASE WHEN (tblNoteRecipients.CompletedDate IS NULL) THEN 0 ELSE 1 END
ELSE
1
END = 1)
OR ((#ShowOpen = 1) AND (#ShowClosed = 1))
)
So my question is how can I make same drop-down list in SSRS?
What would be the data-set in order to populate this drop-down list?
create a parameter in ssrs with 3 static values(open closed both)
in where clause it should be something like :
( #DairyStatus = 'open' and ((tblNoteRecipients.CompletedDate IS NULL and tblNoteRecipients.IsDiary = 1) or tblNoteRecipients.UserGUID is null)) or
( #DairyStatus = 'closed' and tblNoteRecipients.CompletedDate IS not NULL) or
#DairyStatus = 'both'

Conditional WHERE clause to combine two queries

I have a large SELECT INTO statement in a T-SQL script and currently I have two separate SELECT INTO's only differing by one OR condition in the WHERE clause. If my variable #cycle_nbr = 1 I have it doing one SELECT INTO, if #cycle_nbr = 0 I have it doing the other SELECT INTO.
I was wondering if there was a way to do this in one SELECT INTO with the #cylce_nbr condition in the WHERE itself.
Here is my WHERE clause:
WHERE ((a.gl_indicator = '0' OR a.gl_indicator = '1')
AND (a.gl_ins_type = '1' OR a.gl_ins_type = '3' )
AND rel_file_nbr is NULL
AND a.alpha_line NOT LIKE '%Z'
AND mis_process_dt >= #start_dt
and acctg_cyc_ym = #acctg_cyc)
OR (a.prem_sys_cd='T' AND acctg_cyc_ym = #acctg_cyc )
I only want this last condition OR (a.prem_sys_cd='T' AND acctg_cyc_ym = #acctg_cyc ) in there if #cycle_nbr = 1. Can I put an IF in there somewhere to make this work? Or do I have to stick with the IF(#cycle_nbr = 1) run this select ELSE run the other select?
Include your variable in the OR statement, i.e.,
OR (a.prem_sys_cd='T' AND acctg_cyc_ym = #acctg_cyc AND #cycle_nbr = 1)

how can I have different where condition using case statement?

#HistoryMSBType => This is a variable which can contain any varchar.
Depending upon it's value, i need to have different type of where clause.
How can I achieve this ?
SELECT * FROM stageTable map
WHERE id = 1
CASE #HistoryMSBType
WHEN 'Utilization Other' THEN
AND map.ColumnID = 4
WHEN 'Cost Other' THEN
AND map.ColumnID = 6
ELSE
AND map.ColumnName = #HistoryMSBType
END
SELECT *
FROM stageTable map
WHERE id = 1
AND (
(#HistoryMSBType = 'Utilization Other' AND map.ColumnID = 4)
OR
(#HistoryMSBType = 'Cost Other' AND map.ColumnID = 6)
OR
(isnull(#HistoryMSBType,'') NOT IN ('Utilization Other','Cost Other')
AND map.ColumnName = #HistoryMSBType)
)
You need the ISNULL to make it match the CASE-ELSE exactly, but it won't matter if it can never be null.

Resources