Calculate Date Difference in SQL Server 2019 [duplicate] - sql-server

This question already has answers here:
Possible to store value of one select column and use it for the next one?
(4 answers)
How to use a calculated column to calculate another column in the same query using a subquery
(2 answers)
SQL Server Reference a Calculated Column
(6 answers)
Using CASE on a Calculated Column in SQL Server 2012
(2 answers)
Closed 6 months ago.
I am trying to calculate the date difference and keep getting a column name error. I am new to SQL and learning from books and YouTube. Any assistance would be appreciated. I commented out the code not working
declare #rpDT datetime
set #rpDT = getdate()
SELECT [OrgKey]
,[visID]
,[visPatID]
,[visInternal]
,[visName]
,[visAssignedNS]
,[visAssignedRoom]
,[visAssignedBed]
,[visAdmitDT]
,isnull([visDischargeDT],#rpDT)as disDT
,datediff(day,[visAdmitDT],disDT) as Pt_days
FROM [MH_Pharmacy_Hub].[MC].[dbo_Visits]

SQL Server and most of the RDBMS do not allow to reference column at the same level. The closest equivalent to achieve similar effect is CROSS APPLY:
declare #rpDT datetime = getdate();
SELECT [OrgKey]
,[visID]
,[visPatID]
,[visInternal]
,[visName]
,[visAssignedNS]
,[visAssignedRoom]
,[visAssignedBed]
,[visAdmitDT]
,s.disDT
,datediff(day,[visAdmitDT],s.disDT) as Pt_days
FROM [MH_Pharmacy_Hub].[MC].[dbo_Visits]
CROSS APPLY (SELECT COALESCE([visDischargeDT],#rpDT)) AS s(disDT);

Related

How to Remove Trailing Zeroes from a datetime column in SQL Server [duplicate]

This question already has answers here:
How to cast the DateTime to Time
(3 answers)
Closed 4 years ago.
I have a column in a SQL Server database of datatype DATETIME.
Currently the value is in this format: 2054-12-31T00:00:00.0000000
I want to convert this column values into this format : 2054-12-31T00:00:00
This conversion of value should happen while I select the column in SELECT query statement at run time
DATETIME as stored in SQL Server doesn't have any "format" associated with it - it's stored as a binary, 8 byte value.
In order to convert that binary value into a human-readable format, you need to check out the different styles for CONVERTing a DATETIME column into a string representation: https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017
You're probably looking for style #126 - so you can use this in your SELECT query:
SELECT
CONVERT(VARCHAR(50), YourDateTimeColumn, 126)
and that should do it

Passing variable in Group By in SQL Server [duplicate]

This question already has answers here:
I need to pass column names using variable in select statement in Store Procedure but i cannot use dynamic query
(3 answers)
Where can parameters be used in SQL statements?
(2 answers)
Using SQL parameters to DROP INDEX in C#
(2 answers)
Closed 5 years ago.
How can I pass variable in Group BY expression.Here is my code.
and from #Varientsku I want to pass column name
Create Proc spIsUnique
#varientsku nvarchar(max) output
As
Begin
select #varientsku,
IIf (count(*)>1,'Dublicate','True') as Total from product group by
#varientsku
End.
and I get this error.
Each GROUP BY expression must contain at least one column that is not an outer reference.
Help me to solve this
You need dynamic sql
EXEC ('select '+#varientsku+',
IIf (count(*)>1,''Duplicate'',''True'') as Total
from product
group by '+#varientsku)
Note : Make sure #varientsku is sanitized, this code is vulnerable to sql injection

Correct week number from datepart [duplicate]

This question already has answers here:
Isoweek in SQL Server 2005
(4 answers)
Closed 7 years ago.
The code returns:
set datefirst 1
select datepart(wk,'2016-01-01') - 1
but
set datefirst 1
select datepart(wk,'2015-12-31')
returns..53 :/
But in fact - this is the same week. There is more days belonging to 2015 in this week, so it should be "53" or "1" (the same value) for any dates in this particular week. Is this possible to avieve this without building dedicated procedure to analyse date and adjust returned value ?
I use SQL Server 2005
You probably want iso_week:
set datefirst 1
select datepart(iso_week,'2015-12-31') --53
select datepart(iso_week,'2016-01-01') --53
LiveDemo
EDIT:
Looks like that iso_week is supported from SQL Server 2008+.
Is this possible to avieve this without building dedicated procedure
to analyse date and adjust returned value ?
Probably you need to write custom code to calculate it.

Explicit conversion of datetime2 to timestamp in SQL Server [duplicate]

This question already has answers here:
UNIX_TIMESTAMP in SQL Server
(9 answers)
Closed 7 years ago.
I am working with a query in SQL Server:
select datetimevalue
from temp;
Here datetimevalue column's datatype is datetime2 and I need to convert this value into timestamp.
In MySQL if I simply write:
select UNIX_TIMESTAM(datetimevalue)
from temp;
then it returns timestamp.
Is there any way to convert datetime in timestamp explicitly in SQL Server 2014?
SQL Server doesn't have a timestamp type. It used to have one in old versions but that type IS NOT a date & time value. In current versions timestamp is a deprecated synonym for rowversion.

How to take out everything before dash(-) in SQL Server? [duplicate]

This question already has answers here:
getting all chars before space in SQL SERVER
(2 answers)
Closed 8 years ago.
I want to extract a certain part of a row. if there is something like this ..." abcd - productA", " zas1234 - productC", how do I extract everything before the dash(-)?
I tried a left(column name,'-') it didnt work. I am on SQL Server 2012.
The column from which I am trying to extract is a varchar column.
It would be great if someone could help me.
Try this,
select SUBSTRING(column_name, 1, CHARINDEX('-', column_name)-1) from table_name;
DECLARE #varStr VARCHAR(MAX)
SET #varStr='abcd - productA'
SELECT CHARINDEX('-',#varStr)
SELECT LEFT(#varStr,CHARINDEX('-',#varStr)-1)

Resources