Correct week number from datepart [duplicate] - sql-server

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.

Related

Calculate Date Difference in SQL Server 2019 [duplicate]

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);

How to Subtract 119 days from current date in Sql Server [duplicate]

This question already has answers here:
How to subtract 30 days from the current date using SQL Server
(4 answers)
Closed 5 years ago.
I want to subtract 119 days from given date,
i tried dateadd function but it is not working.
select dateadd(dd,-119,'09/05/2017')
DATEADD is correct - I don't know how you have used it, but this would be the way:
SELECT DATEADD(day, -119, #givenDate)
Just saying "it is not working" doesn't help. From what I gather, it does work, but you don't know the syntax. Try this -
SELECT dateadd(d,-119,getdate())

MS SQL Server is dropping 1 millisecond from converted time [duplicate]

This question already has answers here:
Why is SQL Server losing a millisecond?
(6 answers)
Closed 5 years ago.
The following query:
select convert(datetime, '2016-06-20 7:22:52.728')
gives me:
2016-06-20 07:22:52.727
In SQL Server v12.0.4100.1.
Whatever value I put for milliseconds, the result always has 1 less millisecond.
Am I missing something or is this a bug?
It's not a bug. The resolution of datetime is such that the final digit can only be one of a few values... Rounded to increments of .000, .003, or .007 seconds.
This is documented: Microsoft documentation for datetime (Transact-SQL)
That is how datetime works in sql server. If you want that millisecond, switch to datetime2([3-7]).
datetime accuracy is to 0.00333 second.
datetime2 accuracy is to 100 nanoseconds.
Date and Time Data Types and Functions (Transact-SQL)
Similarly, if you want to get the server time with additional accuracy, you would use sysdatetime() which returns datetime2(7) instead of getdate() which returns datetime.

Why is selecting date slow [duplicate]

This question already has answers here:
Performance of SQL Server 2005 Query
(3 answers)
Closed 7 years ago.
I have a table with about 1.5 million rows with date_run is indexed non cluster. Query #1 takes 0 second to finish and query #2 takes 3 seconds. Can someone please explain why query #2 runs slower. I also included execution plans for both. Sql server version 2014.
query #1
select avg14gain
from stocktrack
where
date_run >= '2013-3-21'
and date_run < '2013-3-22'
Valid XHTML http://biginkz.com/Pics/DateHardCoded.jpg.
query #2
declare #today date
declare #yesterday date
set #today='2013-3-22'
set #yesterday='2013-3-21'
select avg14gain
from stocktrack
where
date_run >= #yesterday
and b.date_run <#today
Valid XHTML http://biginkz.com/Pics/DataAsigned.jpg.
I am not sure why your query is not picking up the index, but you can use an index hint.
Try something like this:
declare #today date
declare #yesterday date
set #today='2013-3-22'
set #yesterday='2013-3-21'
select avg14gain
from stocktrack
where
date_run >= #yesterday
and b.date_run <#today
with (index([stocktrack].[ix_drun]))
also you can try what is suggested in this post: TSQL not using indexes.
See #Justin Dearing's answer (rebuild index / update statistics).
Create an index on date_run, with avg14gain as an INCLUDE column on that index. That way the entire query can be satisfied from the one index, and the optimizer will see that.

Change the following to take in account for the new year

I'm very new to sql so im not sure how i would go about changing the line below to take in account for the new year. The sql server query i'm running will run on January 1st of 2014. Will this work in sql server 2008 or will it need to be changed for the new year to capture 2013?
DT.[DOS-DATE] between convert(date,GETDATE()-7) and convert(date,GETDATE())
This query takes records between the last 7 days and today. The year does not matter in that condition.
It's better to use explicit operators on date. Also, no reason to call GETDATE() twice. Try this instead:
DECLARE #Now DATETIME = GETDATE()
...
DT.[DOS-DATE] between convert(date,DATEADD(day, -7, #Now)) and convert(date,#Now)
However, technically your existing code will work.
Also, you may want to take a look at this for potential issues with using BETWEEN:
What do BETWEEN and the devil have in common?

Resources