sql case statement with date values - sql

I have a date column in my database table.
SELECT sDestructionDate FROM tblDocumentHeader
below is the result of above query
I need to print empty for the date value '1991-01-01'
I expect a result set something like below.
I tried the below query but it still print that '1991-01-01' date.
SELECT CASE CONVERT(date,h.sDestructionDate,103)
WHEN '01/01/1991'
THEN ''
ELSE CONVERT(date,h.sDestructionDate,103) END
AS 'sDestructionDate'
FROM tblDocumentHeader h
I don't want to convert the result into varchar value. below query does gives me the result but i need to return it from date format.
SELECT CASE CONVERT(varchar,h.sDestructionDate,103)
WHEN '01/01/1991'
THEN ''
ELSE convert(varchar,h.sDestructionDate,103) END
AS 'sDestructionDate'
FROM tblDocumentHeader h

I would first convert it to a null:
select
case
when h.sDestructionDate = '01/01/1991' then null
else h.sDestructionDate
end as sDestructionDate
from tblDocumentHeader h
Then look to your reporting tool to present a blank if the value is null
Mixing data with presentation is a mistake. This approach is simple and keeps the two concerns of data and rendering separate.

Related

How to use Decode Function in the case where column has string values

I have a view xxabc_v (shown below), I need to update the "Code" column to Null wherever it is N/A when "Value" column sum (900+(-900)=0) becomes zero for the "field_name" values (Demand A+Demand B) for the "Date" 01-Apr-21.
How can I put the decode logic to code column in the above case?
Table structure and expected output:
You don't want decode() because a much simpler method works:
select nullif(code, 'N/A')
This returns NULL when code takes on the specified value.
If you actually want to change the data, then you want update:
update t
set code = NULL
where code = 'N/A';
EDIT:
I see, you have an extra condition. So, use case:
(case when code = 'N/A' and
sum(value) over (partition by id, date) = 0
then NULL
else code
end)
I assumed that you need date wise id wise sum when to sum(). Please check this out:
select date,id,(case when sum(value)over(partition by date,id)=0 and code='N/A' then NULL
else Code end)code, field_name,value
from tablename

SQL - Error converting date and/or time from character string

I have a datetime column which I'm checking for null. All I want to do is have it say "No Next Appointment" if the column is null. However I'm getting an error:
conversion failed when converting date and/or time from character string
I'm not sure why. I tried a couple different ways to write the query but it keeps giving me the same error.
Here is my query-
SELECT
t1.PatientID,
t1.FullName,
t1.CurrentRAF_DW,
t1.NumberOfCompletedClinicVisits,
t1.PreferredServiceLocation,
case when t1.IsVip = 1 then 'Yes' else 'No' end as [IsVip],
case when t1.PatientTier = 'Critical' then 'Every Three Weeks'
when t1.PatientTier = 'Serious' then 'Every 1 Month'
when t1.PatientTier = 'Fair' then 'Every 2 Months'
when t1.PatientTier = 'Good' then 'Every 3 Months'
else ' '
end as [Cadence],
t1.PatientTier,
t2.hcc_18,
t2.hcc_19,
t2.hcc_21,
t2.hcc_22,
t2.hcc_12,
t2.hcc_136,
t2.hcc_137,
t2.hcc_108,
t2.hcc_88,
t2.hcc_111,
t2.hcc_85,
t2.hcc_55,
t1.LastCompletedClinicVisit,
case when t1.NextScheduledClinicVisit is not null then t1.NextScheduledClinicVisit else 'No Next Appointment' end as [NextScheduledVisit]
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
ON t1.PatientID = t2.emr_id
The column in question here is "NextScheduledClinicVisit".
First, you should use coalesce(). Second, the types should match:
coalesce(convert(varchar(255), t1.NextScheduledClinicVisit ),
'No Next Appointment'
) as [NextScheduledVisit]
If NextScheduledClinicVisit is a sting, then you probably want to use an appropriate conversion specification (such as 121) or use format().
The column will sometimes contain a datetime field and sometimes a string.
Try casting the datetime to a varchar.
I'd go about solving your issue using the following method.
Wrap the error generating column in a try_convert and review some sample records
If above successful write your case statement using a "case when [col] is null then 'formatted text 1' ..." type statement and review some sample records
Apparently Gordon's answer is working so use that, but I might look into try_Convert for future reference.

Separate sql value from one field

I have this:
**value**
S:581930640 | P:581930640
And I would like to get the value as in Oracle:
**valuaA ValueB**
581930640 581930640
select
case
when field like 's:%'
then substr(field,3,13)
else null
end as A,
case
when field like 's:%'
then substr(field,17)
else null
end as B
from table;
both the case condition are same, but the substring is different, this should do what you are trying to do.

Dynamic where clause based on variable

I am working on a select statement in SQL and am running into issues trying to create a where clause that includes a case statement or an if else statement. I want to select records based on the value of a variable. If the variable is 'True' then only return records from the select statement where a column is null. If the variable is not 'True' then return all records regardless if that columns is null.
Any tips on how to do this?
Below is a simple example of what i am trying to do:
declare #option1 as varchar(5)
--This can be True or False so to test i just put the Set option below
set #option1 = 'True'
Select a,b,c,d...
from ...
where d = case when #option1 = 'True' then NULL End
This is the part where i do not know what to do. I only need to filter out the records if the variable is 'True' so not sure what to put in the else section of the case.
You can't test for d = NULL as your CASE statement does because that will always return false since NULL is not equal to NULL (unless you set ANSI_NULLS to 'off').
The simplest thing to do would be to change the WHERE clause to this:
WHERE #option1 = 'False' OR d IS NULL
If you prefer to use a CASE statement for some reason, you can write it like this:
WHERE 1 = CASE WHEN #option1 = 'False' THEN 1
WHEN #option1 = 'True' AND d IS NULL THEN 1
ELSE 0
END
This:
UPDATE: PinnyM has straightened me out on this. I am leaving my embarrassing logically flawed argument here for the education of the masses. The solution I propose below after "Try this" is certainly still valid, but PinnyM's solutions is by far more elegant and should be used.
WHERE #option1 = 'False' OR d IS NULL
Will always return all the results given his current select statement (assuming #Option1 is simply a flag parameter passed in).
Try this:
SELECT a, b, c, d
WHERE
-- Returns only rows where d is null (if #Option1 is True)
(#Option1 = 'True' AND d IS NULL)
OR
-- returns all the rows (if #Option1 is False)
(#Option1 = 'False')

SQL Computer Column Formula

A SQL Table (Trades) has three fields AvgProfit, MinProfit and Hold - Hold is a Computed Colum...
If AvgProfit < MinProfit, Hold = 'Hold' and if AvgProfit > MinProfit, Hold = 'Trade'
The Computed Col formula for Hold is as follows.
SQL Table Trades
AvgProfit varchar(35)
MinProfit varchar(35)
Hold varchar(35)
(case when CONVERT([decimal](8,4),isnull([AvgProfit],(0)),(0))>=CONVERT([decimal](8,4),isnull([MinProfit],(0)),(0)) then 'Trade' else 'Hold' end)
PROBLEM: Updates cause the AvgProfit to be empty at times and this results in an error when the table references the Hold formula
'Error Converting varchar to numeric'
How do I add IS NULL or EMPTY to the above formula, the ISNULL does not catch AvgProfit = '' ??
Consider typing your database with decimal or numeric columns as paxdiablo has suggested. Is there a reason why those columns are set as varchar?
Alternatively if you have to keep your varchar columns, try ISNUMERIC(), http://msdn.microsoft.com/en-us/library/ms186272.aspx. It works with all common SQL numeric types. So you query might become:
ISNUMERIC can be used like this:
select case when ISNUMERIC('123') = 1 then 1 else 0 end ' returns 1
select case when ISNUMERIC('xyz') = 1 then 1 else 0 end ' returns 0
select case when ISNUMERIC(null) = 1 then 1 else 0 end ' returns 0
So your query might become:
case when isnumeric(AvgProfit) = 1 THEN case([AvgProfit] as decimal) else 0 END
Or something similar.
varchar columns should be used for VARiable sized CHARacter columns, not for numeric data.
In other words, they shouldn't be empty (other than NULL, of course, but you've taken care of that).
If you cannot fix that little oversight for some reason, you can make your queries even more complex and slower :-) by doing something like:
select case when xyz = '' then 0 when isnull(xyz) then 0 else xyz end ...
In other words, check for both NULL and empty varchar values.
Myself,I'd fix the schema since it'll be better for you in the long term. I'm merely offering the other solution on the chance that you're not able to do that.