I am a self learner in SQL; I have created this code:
SELECT T0.[CardName], T0.[DocDate], T0.[DocDueDate], T2.[U_ExpDelDate], T0.[DocStatus], T1.[SlpName],
CASE
WHEN DATEDIFF(day,DocDueDate,T2.[U_ExpDelDate]) <= 0 THEN 'Delivered'
WHEN DATEDIFF(day,DocDueDate,T2.[U_ExpDelDate]) >= 0 THEN 'Please Check'
ELSE NULL END AS 'Status',
DATEDIFF(day,DocDueDate,T2.[U_ExpDelDate]) AS 'Age'
FROM OPOR T0 INNER JOIN OSLP T1 ON T0.[SlpCode] = T1.[SlpCode] INNER JOIN POR1 T2 ON T0.[DocEntry] = T2.[DocEntry]
WHERE T0.[DocStatus] ='O' and T2.[U_ExpDelDate] is not null
I am getting the right result, but now I wanted Join the result Delivered and Please Check in Age column.
Do you have any idea?
Concatenating strings in sql server is done by either using the + operator or the CONCAT method.
Try this:
SELECT T0.[CardName], T0.[DocDate], T0.[DocDueDate], T2.[U_ExpDelDate], T0.[DocStatus], T1.[SlpName],
CASE
WHEN DATEDIFF(day,DocDueDate,T2.[U_ExpDelDate]) <= 0 THEN 'Delivered '
WHEN DATEDIFF(day,DocDueDate,T2.[U_ExpDelDate]) > 0 THEN 'Please Check ' + CAST(DATEDIFF(day,DocDueDate,T2.[U_ExpDelDate]) as varchar)
END AS 'Age'
FROM OPOR T0 INNER JOIN OSLP T1 ON T0.[SlpCode] = T1.[SlpCode] INNER JOIN POR1 T2 ON T0.[DocEntry] = T2.[DocEntry]
WHERE T0.[DocStatus] ='O' and T2.[U_ExpDelDate] is not null
I've removed the else part since it's never going there, the datediff function will either return a value that is less than or equal to 0 or more than 0.
Related
Sorry to bother everyone with what should be a trivial question, but I need to import an SQL query into SSRS's Report builder, and then turn it into an expression (so that I can use its concatenation operator to join values of a parameter into search strings).
As a first stage, I copied and pasted my query (which I know works) into SSRS, and it ran smoothly. However, as soon as I put the expression in quotes, and prefixed the whole thing with "=", I get some very unhelpful syntax error messages.
This is my (correctly functioning) query before importing into SSRS:
DECLARE #From Date='1/1/2015'
DECLARE #To Date='1/3/2020'
DECLARE #Doctors varchar(5)='ABC'
DECLARE #Intents varchar(20)='RoutineRad-Cat2'
DECLARE #DiagnosisTypes varchar(20)='ICD-10'
SET transaction isolation level read uncommitted;
SELECT
x.Expression1 as 'Intent',
x.IntentCategory,
x.StartDateTime as 'Ready To Start Treatment Date',
x.LastName as 'Surname',
x.PatientId as 'Patient ID',
x.DoctorId as 'Primary Oncologist',
x.TreatmentStartTime as 'First RT Treatment Date',
datediff(dd, x.StartDateTime, x.TreatmentStartTime) as 'Wait in days',
x.TargetMet,
x.Delayed,
x.TxStartSortDate
FROM (VALUES('C50%'),('D05%'),('C61%'))
AS v (pattern)
CROSS APPLY
(
SELECT
lut.Expression1,
p.PatientId,
p.LastName,
c.StartDateTime,
d.DoctorId,
rh.TreatmentStartTime,
CASE
WHEN Expression1 like '%Rad%' THEN 'Radical'
WHEN Expression1 like '%Pall%' THEN 'Palliative'
WHEN Expression1 = 'Emergency' THEN 'Emergency'
ELSE 'Other'
END
as 'IntentCategory',
CASE WHEN Expression1 like '%Delay%' THEN 1 ELSE 0 END as 'Delayed',
CASE WHEN
(
(Expression1 like '%Rad%' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 28)
OR (Expression1 like '%Palliative%' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 14)
OR (Expression1 = 'Emergency' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 1)
--catch any exceptions
OR ((Expression1 not like '%Rad%') AND (Expression1 not like '%Palliative%') AND (Expression1!='Emergency'))
) THEN 1 ELSE 0 END as 'TargetMet',
FORMAT(rh.TreatmentStartTime,'yyyyMM') as 'TxStartSortDate',
FirstRadiationHstry.TreatmentStartTime as 'MinTreatStart',
datediff(dd, c.StartDateTime, rh.TreatmentStartTime) as 'TreatDelay'
FROM
dbo.Patient p
inner join Course c on (c.PatientSer = p.PatientSer)
inner join CourseDiagnosis cd on (cd.CourseSer=c.CourseSer)
inner join Diagnosis diag on (diag.DiagnosisSer=cd.DiagnosisSer)
inner join PatientDoctor pd on (pd.PatientSer = p.PatientSer)
inner join Doctor d on (d.ResourceSer = pd.ResourceSer)
inner join dbo.PhysicianIntent phi on (phi.CourseSer = c.CourseSer)
inner join dbo.LookupTable lut on (lut.LookupValue = phi.TreatmentIntentType and lut.ListSelector = 'COURSE_INTENT')
inner join dbo.PlanSetup ps on (ps.CourseSer = c.CourseSer)
inner join dbo.Radiation r on (r.PlanSetupSer = ps.PlanSetupSer)
inner join dbo.RadiationHstry rh on (rh.RadiationSer = r.RadiationSer)
inner join (
select distinct
min(rh_sub.TreatmentStartTime) over (partition by ps_sub.CourseSer) as 'TreatmentStartTime',
ps_sub.CourseSer
from
RadiationHstry rh_sub
inner join dbo.Radiation r_sub on (r_sub.RadiationSer = rh_sub.RadiationSer)
inner join dbo.PlanSetup ps_sub on (r_sub.PlanSetupSer = ps_sub.PlanSetupSer)
where
rh_sub.TreatmentDeliveryType like 'TREATMENT'
) as FirstRadiationHstry on (FirstRadiationHstry.CourseSer = c.CourseSer)
WHERE
datediff(dd, #From, rh.TreatmentStartTime) >= 0
and datediff(dd, rh.TreatmentStartTime, #To)>=0
and diag.DiagnosisCode like v.pattern
and d.OncologistFlag=1
and d.DoctorId in (#Doctors)
and rh.TreatmentStartTime = FirstRadiationHstry.TreatmentStartTime
and lut.Expression1 in (#Intents)
and diag.DiagnosisTableName in(#DiagnosisTypes)
and lut.Expression1 not like 'Dummy Course'
) AS x
;
...and this is it after:
="SET transaction isolation level read uncommitted;
SELECT
x.Expression1 as 'Intent',
x.IntentCategory,
x.StartDateTime as 'Ready To Start Treatment Date',
x.LastName as 'Surname',
x.PatientId as 'Patient ID',
x.DoctorId as 'Primary Oncologist',
x.TreatmentStartTime as 'First RT Treatment Date',
datediff(dd, x.StartDateTime, x.TreatmentStartTime) as 'Wait in days',
x.TargetMet,
x.Delayed,
x.TxStartSortDate
FROM (VALUES('C50%'),('D05%'),('C61%'))
AS v (pattern)
CROSS APPLY
(
SELECT
lut.Expression1,
p.PatientId,
p.LastName,
c.StartDateTime,
d.DoctorId,
rh.TreatmentStartTime,
CASE
WHEN Expression1 like '%Rad%' THEN 'Radical'
WHEN Expression1 like '%Pall%' THEN 'Palliative'
WHEN Expression1 = 'Emergency' THEN 'Emergency'
ELSE 'Other'
END
as 'IntentCategory',
CASE WHEN Expression1 like '%Delay%' THEN 1 ELSE 0 END as 'Delayed',
CASE WHEN
(
(Expression1 like '%Rad%' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 28)
OR (Expression1 like '%Palliative%' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 14)
OR (Expression1 = 'Emergency' AND datediff(dd, c.StartDateTime, FirstRadiationHstry.TreatmentStartTime) <= 1)
--catch any exceptions
OR ((Expression1 not like '%Rad%') AND (Expression1 not like '%Palliative%') AND (Expression1!='Emergency'))
) THEN 1 ELSE 0 END as 'TargetMet',
FORMAT(rh.TreatmentStartTime,'yyyyMM') as 'TxStartSortDate',
FirstRadiationHstry.TreatmentStartTime as 'MinTreatStart',
datediff(dd, c.StartDateTime, rh.TreatmentStartTime) as 'TreatDelay'
FROM
dbo.Patient p
inner join Course c on (c.PatientSer = p.PatientSer)
inner join CourseDiagnosis cd on (cd.CourseSer=c.CourseSer)
inner join Diagnosis diag on (diag.DiagnosisSer=cd.DiagnosisSer)
inner join PatientDoctor pd on (pd.PatientSer = p.PatientSer)
inner join Doctor d on (d.ResourceSer = pd.ResourceSer)
inner join dbo.PhysicianIntent phi on (phi.CourseSer = c.CourseSer)
inner join dbo.LookupTable lut on (lut.LookupValue = phi.TreatmentIntentType and lut.ListSelector = 'COURSE_INTENT')
inner join dbo.PlanSetup ps on (ps.CourseSer = c.CourseSer)
inner join dbo.Radiation r on (r.PlanSetupSer = ps.PlanSetupSer)
inner join dbo.RadiationHstry rh on (rh.RadiationSer = r.RadiationSer)
inner join (
select distinct
min(rh_sub.TreatmentStartTime) over (partition by ps_sub.CourseSer) as 'TreatmentStartTime',
ps_sub.CourseSer
from
RadiationHstry rh_sub
inner join dbo.Radiation r_sub on (r_sub.RadiationSer = rh_sub.RadiationSer)
inner join dbo.PlanSetup ps_sub on (r_sub.PlanSetupSer = ps_sub.PlanSetupSer)
where
rh_sub.TreatmentDeliveryType like 'TREATMENT'
) as FirstRadiationHstry on (FirstRadiationHstry.CourseSer = c.CourseSer)
WHERE
datediff(dd, #From, rh.TreatmentStartTime) >= 0
and datediff(dd, rh.TreatmentStartTime, #To)>=0
and diag.DiagnosisCode like v.pattern
and d.OncologistFlag=1
and d.DoctorId in (#Doctors)
and rh.TreatmentStartTime = FirstRadiationHstry.TreatmentStartTime
and lut.Expression1 in (#Intents)
and diag.DiagnosisTableName in(#DiagnosisTypes)
and lut.Expression1 not like 'Dummy Course'
) AS x
;"
...but I just get the error message "Incorrect syntax near the keyword 'VALUES'.
Incorrect syntax near ')'."
I have no idea how to go about trying to iron this out, as I know my SQL is fine. I've tried importing the query into Scite and looked at the line endings / special characters, but this looks OK as well.
Can someone please help me?
Best wishes
C J
It seems that you will need to wrap EACH LINE with quotes and link with & to make this work. I haven't been able to figure out why. I also use a Line Feed to break the lines up in the resulting query.
="SET transaction isolation level read uncommitted; " & VBCRLF
" " & VBCRLF
"SELECT " & VBCRLF
" x.Expression1 as 'Intent', " & VBCRLF
" x.IntentCategory, " & VBCRLF
…
In Notepad++ you can Find \r\n and replace with " & VBCRLF & \n" to add them automagically - though you'll need to do the first and last ones.
Source: Couldn't find any - trial and error.
SELECT
rec.CONSTITUENT_ID as 'RE Const ID',
CASE
WHEN soft.giftID IS NULL AND con.first_name IS NULL
THEN con.Key_Name
WHEN soft.giftID IS NULL AND con.first_name IS NOT NULL
THEN con.first_name + ' ' + con.KEY_NAME
WHEN soft.giftID IS NOT NULL AND con3.first_name IS NULL
THEN con3.Key_Name
WHEN soft.giftID IS NOT NULL AND con3.first_name IS NOT NULL
THEN con3.first_name + ' ' + con3.KEY_NAME
END as 'Constituent Name',
gift.usergiftid AS 'RE Gift ID',
CONVERT(varchar(12),gift.dte, 10) AS 'Gift Date',
(CASE
WHEN soft.amount IS NULL
THEN gift.amount
WHEN soft.amount IS NOT NULL
THEN soft.amount
END) AS 'Total Gift Amount',
CASE
WHEN soft.ConstitID IS NOT NULL
THEN 'Yes'
ELSE 'No'
END AS 'Soft Credited?'
FROM
dbo.gift gift
LEFT OUTER JOIN
dbo.GiftSoftCredit soft ON soft.giftID = gift.id and soft.giftID IS NOT NULL
LEFT OUTER JOIN
dbo.records rec ON (CASE WHEN soft.giftID IS NOT NULL THEN soft.ConstitID WHEN soft.giftID IS NULL THEN gift.constit_ID END) = rec.ID
LEFT OUTER JOIN
dbo.constituent con ON con.records_ID = rec.ID
AND con.spousename = '0'
AND con.sequence = '0'
AND soft.GiftID IS NULL
LEFT OUTER JOIN
dbo.constituent con3 ON con3.RECORDS_ID = rec.id
AND soft.GiftID IS NOT NULL
AND con3.spousename = 0
AND con3.sequence = 0
LEFT OUTER JOIN
dbo.GiftSolicitor sol ON sol.parentID = gift.id AND sol.sequence = 1
LEFT OUTER JOIN
dbo.constituent con2 ON con2.RECORDS_ID = sol.SolicitorId
AND con2.sequence = 0
AND con2.spousename = 0
WHERE
gift.dte BETWEEN '2016-10-01' AND '2016-10-08'
AND gift.amount > 0.0000
AND con2.records_ID IS NULL
AND gift.type IN ('1','2','3','31')
Second portion that causes this not to work
AND rec.constituent_ID NOT IN
(SELECT distinct rec.constituent_ID
FROM dbo.gift gift
LEFT OUTER JOIN dbo.GiftSoftCredit soft ON soft.giftID = gift.id
LEFT OUTER JOIN dbo.records rec ON (CASE WHEN soft.giftID IS NOT NULL THEN soft.ConstitID WHEN soft.giftID IS NULL THEN gift.constit_ID END) = rec.ID
WHERE gift.dte BETWEEN '1991-01-01' AND '2016-09-30')
The goal is that I will get records from the top portion of the query that are not in the subquery at the bottom.
When I run the top portion of the sql on its own, I get 478 records. when I run the select in the bottom portion of the code I get 100970 records. When I compare these lists in excel with a vlookup, there are 173 constituent_id records that are not in that sub-query. But when I run the query all together I get NO records.
I have no idea what I am doing wrong here and I am still learning to a large degree with some of this, but I have no one to go to for help because I am all self-taught. I'm hoping I can get some help here.
I am on SQL Server 2008 R2 (SP2).
From this link: NOT IN clause and NULL values
select 'true' where 3 not in (1, 2, null) returns nothing, and your SQL could return NULLs for the rec.constituent_ID column in your final section.
Would the logic still be valid if you change the LEFT OUTER JOINS to INNER JOINS? INNER JOINS would remove the NULLs.
SELECT
ROW_NUMBER() OVER (ORDER BY Vendor_PrimaryInfo.Vendor_ID ASC) AS RowNumber,
*
FROM
Unit_Table
INNER JOIN
Vendor_Base_Price ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID
INNER JOIN
Vendor_PrimaryInfo ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID
INNER JOIN
Vendor_Registration ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID
AND Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID
INNER JOIN
Category_Table ON Vendor_Registration.Category_ID = Category_Table.Category_ID
LEFT JOIN
Vendor_Value_Table ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID
LEFT JOIN
Feature_Table ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID
WHERE
Vendor_Registration.Category_ID = 5
AND Vendor_PrimaryInfo.City = 'City'
AND (value_text in ('sample value') or
(SELECT
CASE WHEN ISNUMERIC(value_text) = 1
THEN CAST(value_text AS INT)
ELSE -1
END) BETWEEN 0 AND 100)
As column has multiple values which may be text or may be int that's why I cast based on case. My question is: I just want to fetch the records either whose value is between 0 and 100 or value between 300 to 400 or value is like sample value.
I just want to place the condition after where clause and do not want to use column_name multiple time in between operator because these values are coming from url
Thanks in advance any help would be grateful.
You can try this way..
WHERE
Vendor_Registration.Category_ID = 5
AND Vendor_PrimaryInfo.City = 'City'
AND (value_text in ('sample value') or
(CASE WHEN (ISNUMERIC(value_text) = 1)
THEN CAST(value_text AS INT)
ELSE -1
END) BETWEEN 0 AND 100)
I have created a select query that contains one regular table and two derived tables (subqueries). The derived tables are both joined with the regular table with left joins. The regular table contains over 7000 rows, but the query output is around 3000 rows. It has to be equal to the number of records in the regular table. What is my mistake?
SELECT T0.[ItemCode],
T0.[ItemName],
CASE T0.[PrcrmntMtd] WHEN 'B' THEN 'Inkoop' ELSE 'Productie' END AS Verwervingsmethode,
T0.[OnHand] AS Voorraad_excl_grondstof_reeds_verwerkt,
T1.[Reeds_geproduceerd] AS Grondstof_reeds_verwerkt,
CASE WHEN T1.[Reeds_geproduceerd] IS NULL
THEN T0.[OnHand]
ELSE T0.[OnHand]-T1.[Reeds_geproduceerd]
END AS Voorraad_incl_grondstof_reeds_verwerkt,
T2.[Nog_te_produceren] AS Geplande_productie_halffabrikaat_eindproduct,
T1.[Nog_te_produceren] AS Gereserveerd_voor_productie_grondstof_halffabrikaat,
CASE WHEN T1.[Reeds_geproduceerd] IS NULL
THEN (T0.[OnHand]/T2.[Nog_te_produceren])*30
ELSE ((T0.[OnHand]-T1.[Reeds_geproduceerd])/T2.[Nog_te_produceren])*30
END AS Dagen_voorraad_halffabrikaat_eindproduct,
CASE WHEN T1.[Reeds_geproduceerd] IS NULL
THEN (T0.[OnHand]/T1.[Nog_te_produceren])*30
ELSE ((T0.[OnHand]-T1.[Reeds_geproduceerd])/T1.[Nog_te_produceren])*30
END AS Dagen_voorraad_grondstof_halffabrikaat
FROM OITM T0
LEFT JOIN (
SELECT T1.[ItemCode],
SUM(T0.[PlannedQty]*T1.[BaseQty]) AS Geplande_productie,
CASE WHEN SUM(T0.CmpltQty) IS NULL THEN SUM(T0.[PlannedQty]*T1.[BaseQty]) ELSE SUM(T0. [CmpltQty]*T1.[BaseQty]) END AS Reeds_geproduceerd,
CASE WHEN SUM(T0.CmpltQty) IS NULL THEN SUM(T0.[PlannedQty]*T1.[BaseQty]) ELSE SUM(T0.[PlannedQty]*T1.[BaseQty])-SUM(T0.[CmpltQty]*T1.[BaseQty]) END AS Nog_te_produceren
FROM OWOR T0
INNER JOIN WOR1 T1 ON T0.DocEntry = T1.DocEntry
WHERE T0.DueDate <= getdate()+30
AND (T0.[Status] LIKE 'p'
OR T0.[Status] LIKE 'r')
GROUP BY T1.[ItemCode]
) AS T1
ON T0.ItemCode = T1.ItemCode
LEFT JOIN (
SELECT T0.[ItemCode],
SUM(T0.[PlannedQty]) AS Geplande_productie,
SUM(T0.[CmpltQty]) AS Reeds_geproduceerd,
SUM(T0.[PlannedQty])-SUM(T0.[CmpltQty]) AS Nog_te_produceren
FROM OWOR T0
INNER JOIN WOR1 T1 ON T0.DocEntry = T1.DocEntry
WHERE T0.DueDate <= getdate()+30
AND (T0.[Status] LIKE 'p'
OR T0.[Status] LIKE 'r')
GROUP BY T0.[ItemCode]
) AS T2
ON T0.ItemCode = T2.ItemCode
I mentioned all the where clauses. If I red the linked page correct, that cant be the problem.
I also changed the table names and column names of the derived tables. Now all table names and column names are unique.
But still the same problem. When i delete the last two case statements in select, i do get all the output lines, but i dont see any problems in these case statements.
SELECT T0.[ItemCode],
T0.[ItemName],
CASE T0.[PrcrmntMtd] WHEN 'B' THEN 'Inkoop' ELSE 'Productie' END AS Verwervingsmethode,
T0.[OnHand] AS Voorraad_excl_grondstof_reeds_verwerkt,
T3.[Reeds_geproduceerd_grond] AS Grondstof_reeds_verwerkt,
CASE WHEN T3.[Reeds_geproduceerd_grond] IS NULL
THEN T0.[OnHand]
ELSE T0.[OnHand]-T3.[Reeds_geproduceerd_grond]
END AS Voorraad_incl_grondstof_reeds_verwerkt,
T6.[Nog_te_produceren_eind] AS Geplande_productie_halffabrikaat_eindproduct,
T3.[Nog_te_produceren_grond] AS Gereserveerd_voor_productie_grondstof_halffabrikaat,
CASE WHEN T3.[Reeds_geproduceerd_grond] IS NULL
THEN 30*(T0.[OnHand]/T6.[Nog_te_produceren_eind])
ELSE 30*((T0.[OnHand]-T3.[Reeds_geproduceerd_grond])/T6.[Nog_te_produceren_eind])
END AS Dagen_voorraad_halffabrikaat_eindproduct,
CASE WHEN T3.[Reeds_geproduceerd_grond] IS NULL
THEN 30*(T0.[OnHand]/T3.[Nog_te_produceren_grond])
ELSE 30*((T0.[OnHand]-T3.[Reeds_geproduceerd_grond])/T3.[Nog_te_produceren_grond])
END AS Dagen_voorraad_grondstof_halffabrikaat
FROM OITM T0
LEFT JOIN (
SELECT T2.[ItemCode] AS ItemCode_grond,
SUM(T1.[PlannedQty]*T2.[BaseQty]) AS Geplande_productie_grond,
CASE WHEN SUM(T1.CmpltQty) IS NULL
THEN SUM(T1.[PlannedQty]*T2.[BaseQty])
ELSE SUM(T1.[CmpltQty]*T2.[BaseQty])
END AS Reeds_geproduceerd_grond,
CASE WHEN SUM(T1.CmpltQty) IS NULL
THEN SUM(T1.[PlannedQty]*T2.[BaseQty])
ELSE SUM(T1.[PlannedQty]*T2.[BaseQty])-SUM(T1.[CmpltQty]*T2.[BaseQty])
END AS Nog_te_produceren_grond
FROM OWOR T1
INNER JOIN WOR1 T2 ON T1.DocEntry = T2.DocEntry
WHERE T1.DueDate <= getdate()+30
AND (T1.[Status] LIKE 'p'
OR T1.[Status] LIKE 'r')
GROUP BY T2.[ItemCode]
) AS T3
ON T0.ItemCode = T3.ItemCode_grond
LEFT JOIN (
SELECT T4.[ItemCode] AS ItemCode_eind,
SUM(T4.[PlannedQty]) AS Geplande_productie_eind,
SUM(T4.[CmpltQty]) AS Reeds_geproduceerd_eind,
SUM(T4.[PlannedQty])-SUM(T4.[CmpltQty]) AS Nog_te_produceren_eind
FROM OWOR T4
INNER JOIN WOR1 T5 ON T4.DocEntry = T5.DocEntry
WHERE T4.DueDate <= getdate()+30
AND (T4.[Status] LIKE 'p'
OR T4.[Status] LIKE 'r')
GROUP BY T4.[ItemCode]
) AS T6
ON T0.ItemCode = T6.ItemCode_eind
I am getting syntax error in the below code:
I have made it bold where all I am getting an error. I can use the if-else statement but I really wanto use case statement.
Pls help me with the error.
**CASE** #policy_type
WHEN 'car' THEN
(Select policy_id,customer_id,policy_duration,requested_policy_amount,Car_Age
,Car_Amount
,Number_of_Accidents,estimated_car_premium INTO
#PendingRequest FROM [dbo].[Policy] p join [dbo].[Car_Insurance] c on
p.policy_type_id=c.policy_type_id and p.approved_policy_amount is Null
--And employee_id=#employee_id
join
[dbo].[Car_Insurance_Estimate] c_est on car_age >= c_est.min_car_age and car_age <= c_est.max_car_age
and Car_Amount>=c_est.min_car_amount and Car_Amount<=c_est.max_car_amount and Number_of_Accidents>=c_est.min_accidents
and Number_of_Accidents<=c_est.max_accidents)
**WHEN** 'life' THEN
(Select policy_id,customer_id,policy_duration,requested_policy_amount,Age
,l.Illness
,l.Income
,premium_insurance_percentage,amount_insurance_percentage
INTO
#PendingRequest from [dbo].[Policy] p join [dbo].[life_Insurance] l on
p.policy_type_id=l.policy_type_id and p.approved_policy_amount is Null
And employee_id=#employee_id
join
[dbo].[life_Insurance_Estimate] l_est on age >= l_est.min_age and age <= l_est.max_age
and income>=l_est.min_income and income<=l_est.max_income and l.illness=l_est.illness)
when 'home' then
(Select policy_id,customer_id,policy_duration,requested_policy_amount,home_Age
,home_Amount
,h.Area,home_premium_percentage INTO
#PendingRequest
from [dbo].[Policy] p join [dbo].[home_Insurance] h on
p.policy_type_id=h.policy_type_id and p.approved_policy_amount is Null
And employee_id=#employee_id
join
[dbo].[home_Insurance_Estimate] h_est on home_age >= h_est.min_home_age and home_age <= h_est.max_home_age
and home_Amount>=h_est.min_home_amount and home_Amount<=h_est.max_home_amount and h.Area=h_est.area)
**END**
Using IF...ELSE would be a lot easier in this case. However, if you insist on using CASE, then this might be one option:
DECLARE #SQL varchar(max);
SELECT #SQL=
CASE #policy_type
WHEN 'car' THEN
'Select policy_id,customer_id,policy_duration,requested_policy_amount,Car_Age
,Car_Amount
,Number_of_Accidents,estimated_car_premium INTO
#PendingRequest FROM [dbo].[Policy] p join [dbo].[Car_Insurance] c on
p.policy_type_id=c.policy_type_id and p.approved_policy_amount is Null
--And employee_id=#employee_id
join
[dbo].[Car_Insurance_Estimate] c_est on car_age >= c_est.min_car_age and car_age <= c_est.max_car_age
and Car_Amount>=c_est.min_car_amount and Car_Amount<=c_est.max_car_amount and Number_of_Accidents>=c_est.min_accidents
and Number_of_Accidents<=c_est.max_accidents'
WHEN 'life' THEN
'Select policy_id,customer_id,policy_duration,requested_policy_amount,Age
,l.Illness
,l.Income
,premium_insurance_percentage,amount_insurance_percentage
INTO
#PendingRequest from [dbo].[Policy] p join [dbo].[life_Insurance] l on
p.policy_type_id=l.policy_type_id and p.approved_policy_amount is Null
And employee_id=#employee_id
join
[dbo].[life_Insurance_Estimate] l_est on age >= l_est.min_age and age <= l_est.max_age
and income>=l_est.min_income and income<=l_est.max_income and l.illness=l_est.illness'
WHEN 'home' THEN
'Select policy_id,customer_id,policy_duration,requested_policy_amount,home_Age
,home_Amount
,h.Area,home_premium_percentage INTO
#PendingRequest
from [dbo].[Policy] p join [dbo].[home_Insurance] h on
p.policy_type_id=h.policy_type_id and p.approved_policy_amount is Null
And employee_id=#employee_id
join
[dbo].[home_Insurance_Estimate] h_est on home_age >= h_est.min_home_age and home_age <= h_est.max_home_age
and home_Amount>=h_est.min_home_amount and home_Amount<=h_est.max_home_amount and h.Area=h_est.area'
END
EXEC(#SQL);
Raj
I can use the if-else statement but I really wanto use case statement.
Whenever I see this, I think twice about whether it's a real question being asked. Why?
If you must combine it as one statement, you can put the conditions into the SELECT statements and join them using UNION ALL, only one of which would actually produce results.
--declare #policy_type varchar(10), #employee_id int
Select policy_id,customer_id,policy_duration,requested_policy_amount,Car_Age
,Car_Amount
,Number_of_Accidents,estimated_car_premium
INTO #PendingRequest
FROM [dbo].[Policy] p join [dbo].[Car_Insurance] c on
p.policy_type_id=c.policy_type_id and p.approved_policy_amount is Null
--And employee_id=#employee_id
join
[dbo].[Car_Insurance_Estimate] c_est on car_age >= c_est.min_car_age and car_age <= c_est.max_car_age
and Car_Amount>=c_est.min_car_amount and Car_Amount<=c_est.max_car_amount and Number_of_Accidents>=c_est.min_accidents
and Number_of_Accidents<=c_est.max_accidents
AND #policy_type = 'car'
UNION ALL
Select policy_id,customer_id,policy_duration,requested_policy_amount,Age
,l.Illness
,l.Income
,premium_insurance_percentage,amount_insurance_percentage
from [dbo].[Policy] p join [dbo].[life_Insurance] l on
p.policy_type_id=l.policy_type_id and p.approved_policy_amount is Null
And employee_id=#employee_id
join
[dbo].[life_Insurance_Estimate] l_est on age >= l_est.min_age and age <= l_est.max_age
and income>=l_est.min_income and income<=l_est.max_income and l.illness=l_est.illness
AND #policy_type = 'life'
UNION ALL
Select policy_id,customer_id,policy_duration,requested_policy_amount,home_Age
,home_Amount
,h.Area,home_premium_percentage
from [dbo].[Policy] p join [dbo].[home_Insurance] h on
p.policy_type_id=h.policy_type_id and p.approved_policy_amount is Null
And employee_id=#employee_id
join
[dbo].[home_Insurance_Estimate] h_est on home_age >= h_est.min_home_age and home_age <= h_est.max_home_age
and home_Amount>=h_est.min_home_amount and home_Amount<=h_est.max_home_amount and h.Area=h_est.area
AND #policy_type = 'home';
If it's some silly assignment requirement, then you can make a benign change to the last row, say
AND CASE #policy_type WHEN 'home' then 1 else 0 END = 1;
instead of case , u can use if statement
if #policy_type = 'Car'
BEGIN
Query1
END
ELSE IF (#policy_type = 'life')
BEGIN
Query2
END
and thus ur #table will be accessasble every where