SQL Server Case update not allowing greater than - sql-server

I am trying to update a table based with a status, based on a date base condition, however SSMS is saying the > is incorrect syntax?
UPDATE [Inbound]
SET [Rev Status] = CASE [Rev Status]
WHEN (CONVERT (Date, GETDATE())) > [Rev Date] THEN 'Late'
ELSE 'On Time'
END;
Thanks for your help!

The CASE statement syntax is wrong here, if I am correct, the query would be like this :
UPDATE [Inbound]
SET [Rev Status] = CASE WHEN (CONVERT (Date, GETDATE())) > [Rev Date]
THEN 'Late' ELSE 'On Time'
END;
See detail about CASE here

Related

Select First Record of the Same Record ID Within Multiple Joined Queries

I wrote a query with multiple join statements and would like to only select the top 'PT_FIN' where there are multiple of the same PT_FINs. I'm having an issue in how to embed the code that selects only one PT_FIN within the code I have already written.
I found a few links that provide the answer in selecting only the top row but like I said, I'm having issues making these answers work within my code:
Select the first instance of a record
Selecting the first record out of each nested grouped record
USE EMTCQIData
DECLARE #StartDate Date
DECLARE #EndDate Date
Set #StartDate = '03/01/2018'
Set #EndDate = '03/25/2018'
Select ORD.PT_FIN, NOTE.Tracking_GROUP, NOTE.AUTHOR,
FORMAT(ORD.CHECKIN_DT_TM, 'MM/dd/yyyy') as DOV, ORD.Order_Mnemonic,
ORD.order_status,
CASE WHEN ORDER_MNEMONIC LIKE '%ketamine%' THEN 'YES' ELSE 'NO' END
[KETAMINE ORDERED], ORD.DOSE,
CASE
WHEN NOTE.RESULT LIKE '%99143%' THEN 'YES'
ELSE 'NO'
END BILLED_SEDATION,
CASE
WHEN NOTE2.RESULT LIKE '%Sedation%' THEN 'YES' Else 'NO' END
POWERNOTE_SEDATION
FROM [ED_Orders_Import_Master] AS ORD
INNER JOIN
(
Select *
FROM [ED_NOTES_MASTER] AS NOTE
Where RESULT_TITLE_TEXT = 'ED Physician Charges' AND RESULT_DT_TM >
#StartDate and RESULT_DT_TM < #EndDate
)
as NOTE ON NOTE.PT_FIN = ORD.PT_FIN
INNER JOIN
(
Select *
FROM [ED_NOTES_MASTER] AS NOTE2
Where NOTE_TYPE like '%PowerNote ED%' AND RESULT_DT_TM > #StartDate and
RESULT_DT_TM < #EndDate
)
as NOTE2 ON NOTE2.PT_FIN = ORD.PT_FIN
WHERE [Checkin_dt_tm] > #StartDate and [Checkin_dt_tm] < #EndDate AND
ORDER_MNEMONIC LIKE '%ketamine%' and ORIG_ORD_AS like '%Normal%' and
ORDER_STATUS like '%complete%'
ORDER by ORD.PT_FIN
I would like the results to look like this:
PT_FIN Order Billed Sedation Power Note Sedation
1 Ketamine yes Yes
2 Ketamine yes no
3 Ketamine yes Yes
The database schema and sample input is missing in the question, but it can be an approach, as you only need to validate the existence of the notes, i think that exists can solve your problem. Apply would help too if you need to get more than one value from the correlated sub-queries
DECLARE #StartDate Date
DECLARE #EndDate Date
Set #StartDate = '03/01/2018'
Set #EndDate = '03/25/2018'
Select ORD.PT_FIN, ORDER_MNEMONIC,
CASE WHEN EXISTS(SELECT 1 FROM [ED_NOTES_MASTER] WHERE RESULT_TITLE_TEXT = 'ED Physician' AND PT_FIN = ORD.PT_FIN AND RESULT LIKE '%99143%') THEN 'Yes' ELSE 'NO' END AS BILLED_SEDATION,
CASE WHEN EXISTS(SELECT 1 FROM [ED_NOTES_MASTER] WHERE NOTE_TYPE like '%PowerNote ED%' PT_FIN = ORD.PT_FIN AND RESULT LIKE '%Sedation%') THEN 'Yes' ELSE 'NO' END AS POWER_NOTE_SEDATION
FROM [ED_Orders_Import_Master] AS ORD
WHERE [Checkin_dt_tm] > #StartDate and [Checkin_dt_tm] < #EndDate AND
ORDER_MNEMONIC LIKE '%ketamine%' and ORIG_ORD_AS like '%Normal%' and
ORDER_STATUS like '%complete%'
ORDER by ORD.PT_FIN
Using apply to get the note only if is the first one, I got your current approach and switched your INNER JOINs into OUTER APPLYs with TOP 1 to accomplish what you are asking for in the title
Select ORD.PT_FIN, NOTE.Tracking_GROUP, NOTE.AUTHOR,
FORMAT(ORD.CHECKIN_DT_TM, 'MM/dd/yyyy') as DOV, ORD.Order_Mnemonic,
ORD.order_status,
CASE WHEN ORDER_MNEMONIC LIKE '%ketamine%' THEN 'YES' ELSE 'NO' END
[KETAMINE ORDERED], ORD.DOSE,
CASE
WHEN NOTE.RESULT LIKE '%99143%' THEN 'YES'
ELSE 'NO'
END BILLED_SEDATION,
CASE
WHEN NOTE2.RESULT LIKE '%Sedation%' THEN 'YES' Else 'NO' END
POWERNOTE_SEDATION
FROM [ED_Orders_Import_Master] AS ORD
OUTER APPLY
(
Select TOP 1 *
FROM [ED_NOTES_MASTER]
Where PT_FIN = ORD.PT_FIN
ANd RESULT_TITLE_TEXT = 'ED Physician Charges' AND RESULT_DT_TM >
#StartDate and RESULT_DT_TM < #EndDate
ORDER BY RESULT_DT_TM
)
as NOTE
OUTER APPLY
(
Select TOP 1 *
FROM [ED_NOTES_MASTER]
Where PT_FIN = ORD.PT_FIN NOTE_TYPE like '%PowerNote ED%' AND RESULT_DT_TM > #StartDate and
RESULT_DT_TM < #EndDate
ORDER BY RESULT_DT_TM
)
WHERE [Checkin_dt_tm] > #StartDate and [Checkin_dt_tm] < #EndDate AND
ORDER_MNEMONIC LIKE '%ketamine%' and ORIG_ORD_AS like '%Normal%' and
ORDER_STATUS like '%complete%'
ORDER by ORD.PT_FIN

How do I form a MS SQL Server SELECT Statement to Fill a specific VIEW with EMPTY string, based on a condition

Firstly, thank you in advance to EVERYONE who takes the answers this question.
I have a simple SQL Server view (on an existing table) in SQL Server 2012 Express. The view has two columns of interest, for (printed) reporting purposes.
Both columns are of datatype DATETIME. One is for Departure date-time, the other Arrival date-time.
Now, my questions is this folks. What would be the SELECT clause syntax, so that if either of the datetime columns does not equate to today, the view can create a new column as a blank string?
So, for instance, if ArrivalDate is not equal to today, I wish to not just return that date stored in ArrivalDate, but a BLANK string.
I have included the SELECT statement for the view as it stands now:
SELECT
bookingRef, custName, departureDateTime, arrivalDateTime
FROM
dbo.Bookings
WHERE
(departureDateTime BETWEEN CAST(GETDATE() AS DATE)
AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)))
OR (arrivalDateTime BETWEEN CAST(GETDATE() AS DATE)
AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)))
Am I right in remembering that this task requires variables/parametric utilization???
Right first of all String datatypes can have Empty strings but Date datatype cannot have empty date values, It can have either a date value or NULL value.
You can either return a dummy date like 1900-01-01 or NULL. but you cannot have an empty string in a datetime/date column.
Therefore you can do something like this...
SELECT bookingRef
, custName
, CASE WHEN CAST(departureDateTime AS DATE) <> CAST(GETDATE() AS DATE)
THEN NULL
ELSE departureDateTime END AS departureDateTime
, CASE WHEN CAST(arrivalDateTime AS DATE) <> CAST(GETDATE() AS DATE)
THEN NULL
ELSE arrivalDateTime END AS arrivalDateTime
FROM dbo.Bookings
WHERE CAST(departureDateTime AS DATE) = CAST(GETDATE() AS DATE)
OR CAST(arrivalDateTime AS DATE) = CAST(GETDATE() AS DATE)
Or you can have the datetime column returned in string/character datatype, then you can have empty strings in your final result. you could do something like this...
SELECT bookingRef
, custName
, CASE WHEN CAST(departureDateTime AS DATE) <> CAST(GETDATE() AS DATE)
THEN ''
ELSE CONVERT(VARCHAR(19), departureDateTime, 120)
END AS departureDateTime
, CASE WHEN CAST(arrivalDateTime AS DATE) <> CAST(GETDATE() AS DATE)
THEN ''
ELSE CONVERT(VARCHAR(19), arrivalDateTime, 120)
END AS arrivalDateTime
FROM dbo.Bookings
WHERE CAST(departureDateTime AS DATE) = CAST(GETDATE() AS DATE)
OR CAST(arrivalDateTime AS DATE) = CAST(GETDATE() AS DATE)

Show empty string when date field is 1/1/1900

I'm querying a database like so:
SELECT DISTINCT
CASE WHEN CreatedDate = '1900-01-01 00:00:00.000' THEN '' ELSE CreatedDate END AS CreatedDate
FROM LitHoldDetails
lhd.CreatedDate is a DateTime field and is non-nullable. I want to display an empty string if the field is the minimum date (1/1/1900), but my CASE statement doesn't work; CreatedDate displays 1900-01-01 00:00:00.000 in my query when that value is in the database. I'm using SQL Server 2008 R2. What am I doing wrong?
When you use a CASE expression (not statement) you have to be aware of data type precedence. In this case you can't just set a DATETIME to an empty string. Try it:
SELECT CONVERT(DATETIME, '');
One workaround is to present your date as a string:
CASE WHEN CONVERT(DATE, CreatedDate) = '1900-01-01' -- to account for accidental time
THEN ''
ELSE CONVERT(CHAR(10), CreatedDate, 120)
+ ' ' + CONVERT(CHAR(8), CreatedDate, 108)
END
Or you could fiddle with the presentation stuff where it belongs, at the presentation tier.
Here is an example that works exactly as you seem to want:
DECLARE #d TABLE(CreatedDate DATETIME);
INSERT #d SELECT '19000101' UNION ALL SELECT '20130321';
SELECT d = CASE WHEN CreatedDate = '19000101'
THEN ''
ELSE CONVERT(CHAR(10), CreatedDate, 120)
+ ' ' + CONVERT(CHAR(8), CreatedDate, 108)
END FROM #d;
Results:
d
-------------------
<-- empty string
2013-03-21 00:00:00
select ISNULL(CONVERT(VARCHAR(23), WorkingDate,121),'') from uv_Employee
Try this code
(case when CONVERT(VARCHAR(10), CreatedDate, 103) = '01/01/1900' then '' else CONVERT(VARCHAR(24), CreatedDate, 121) end) as Date_Resolved
If you CAST your data as a VARCHAR() instead of explicitly CONVERTing your data you can simply
SELECT REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan 1 1900 12:00AM','')
The CAST will automatically return your Date then as Jun 18 2020 12:46PM fix length strings formats which you can additionally SUBSTRING()
SELECT SUBSTRING(REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan 1 1900 12:00AM',''),1,11)
Output
Jun 18 2020
Two nitpicks. (1) Best not to use string literals for column alias - that is deprecated. (2) Just use style 120 to get the same value.
CASE
WHEN CreatedDate = '19000101' THEN ''
WHEN CreatedDate = '18000101' THEN ''
ELSE Convert(varchar(19), CreatedDate, 120)
END AS [Created Date]
An alternate solution that covers both min (1/1/1900) and max (6/6/2079) dates:
ISNULL(NULLIF(NULLIF(CONVERT(VARCHAR(10), CreatedDate, 120), '1900-01-01'), '2079-06-06'), '').
Whatever solution you use, you should do a conversion of your date (or datetime) field to a specific format to bulletproof against different default server configurations.
See CAST and CONVERT on MSDN: https://msdn.microsoft.com/en-us/library/ms187928.aspx
Use this inside of query, no need to create extra variables.
CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN '' ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'
Works like a charm.
Simpler method that worked. ISNULL Nested CAST function can remove 1900-1-1 value if data is NULL
ISNULL(CAST(CAST(<<DateColumn>> AS DATE) AS Varchar),' ') [<<Date Column Name>>]

Only Date Part comparison with System Date in SQL Server

I have a stored procedure :-
CREATE procedure St_Proc_GetTimeEntryID
#userID int,
#timeEntryID int output
as begin
set nocount on;
SET #timeEntryID=0
DECLARE #TEMP INT
SET #TEMP=0
SELECT #TEMP=ProductionTimeEntryID
FROM production
WHERE ProductionTimeEntryID =
(SELECT MAX(ProductionTimeEntryID)
FROM production
where UserID=#userID
and (CalendarDate = (select GETDATE()))
and IsTaskCompleted=1 )
BEGIN
SET #timeEntryID=#TEMP
END
END
Here CalendarDate is column which containing Date As 06/26/201212:00PM format .
I want to compare the date part only with system date part (06/26/2012 = 06/26/2012) in my subquery which is
(SELECT MAX(ProductionTimeEntryID)
FROM production
where UserID=#userID
and (CalendarDate = (select GETDATE()))
and IsTaskCompleted=1 )
Please guide me what modification i ll do to get the result.
In SQL2K8;
... WHERE CAST(CalendarDate AS DATE) <= CAST(GETDATE() AS DATE)
(This will negate any index use on CalendarDate, alternatively bracket CalendarDate between CalendarDate >= CAST(CalendarDate AS DATE) AND < DATEADD(...)
The most efficient method (meaning fully able to utilize an index on CalendarDate, if one exists) is going to be, on SQL Server 2000/2005:
DECLARE #today SMALLDATETIME;
SET #today = DATEDIFF(DAY, 0, CURRENT_TIMESTAMP);
...
WHERE CalendarDate >= #today
AND CalendarDate < DATEADD(DAY, 1, #today);
If using SQL Server 2008+:
DECLARE #today DATE = CURRENT_TIMESTAMP;
...
WHERE CalendarDate >= #today
AND CalendarDate < DATEADD(DAY, 1, #today);
You can also use a direct cast in SQL Server 2008+, but I'm not 100% sure this is guaranteed to use an index on CalendarDate in all scenarios:
WHERE CONVERT(DATE, CalendarDate) = CONVERT(DATE, CURRENT_TIMESTAMP);
Because this casting does not work with other date/time data types, for consistency I much prefer the open-ended range technique, and definitely do not condone most of the scenarios where you perform implicit or explicit conversions on the column (since this usually means an index won't be used). I've ranted about this and several other date/time atrocities plenty at the following blog posts:
What do BETWEEN and the devil have in common?
Bad habits to kick : mis-handling date / range queries
Something like this?
(SELECT MAX(ProductionTimeEntryID)
FROM production
where UserID=412
and (convert(datetime, convert(varchar(100), CalendarDate, 106)) <= convert(datetime, convert(varchar(100), GETDATE(), 106)))
and IsTaskCompleted=1 )
Use convert function
In your case:
SELECT CONVERT(DATE,GETDATE(),101)
More specifically:
(SELECT MAX(ProductionTimeEntryID)
FROM production
where UserID=#userID
and (CONVERT(DATE,CalendarDate) = CONVERT(DATE,GETDATE()))
and IsTaskCompleted=1 )

How to make a SQL looping for date?

select CAST(convert(varchar, a.rechargedate, 112) as datetime)as RechargeDate,
COUNT(distinct a.mobileno) AS UnitTotal,
SUM(a.amount) AS AmountTotal
from recharge a
where *a.rechargedate BETWEEN '2009-07-01' AND '2009-07-31'*
group by CAST(convert(varchar, a.rechargedate, 112) as datetime)
order by a.rechargedate
above is my sql query. in the
(((( a.rechargedate BETWEEN '2009-07-01' AND '2009-07-31' )))))
i would change it by using looping. so if next time i wanna change date to august. it will automatically loops by itself. i no need to manually key in the date to 2009-08-01........
got anyone can help me ? show me how to make it?
Not sure if this is just a query that you are using for yourself to veiw data, or if it is suppose to be in a sproc. If it is just a utility query, you could do something like this.,
declare #firstofmonth as smalldatetime
declare #endofmonth as smalldatetime
--Set the inital month to loop
set #firstofmonth = '01/01/2009'
set #endofmonth = '01/31/2009'
WHILE #firstofmonth >= '09/01/2009' --This would be the condition to end the loop
Begin
select CAST(convert(varchar, a.rechargedate, 112) as datetime)as RechargeDate,
COUNT(distinct a.mobileno) AS UnitTotal,
SUM(a.amount) AS AmountTotal
From recharge a
Where a.rechargedate BETWEEN #firstofmonth AND #endofmonth
group by CAST(convert(varchar, a.rechargedate, 112) as datetime)
order by a.rechargedate
SET #firstofmonth = DateAdd(m,1,#firstofmonth)
SET #endofmonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#firstofmonth())+1,0))
End
it all depends on your logic, here are some options:
take #startDate and #endDate as parameters for the sproc
if you can logically tie those dates to current date, you can calculate them in the sproc (or function) based on getdate() (will give you current date)

Resources