DynamicSQL query for date calculation [closed] - dynamic-sql

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
In Dynamic SQL I need to calculate the difference in Date and a Number
Error while running the below query,
Declare #sqlstring VARCHAR(MAX)
Declare #GCValue INT
Set #GCValue=10
set #sqlstring = 'SELECT Id, getdate() - (FirstDate + ' + #GCValue +' ) from
Table where Id=1234'
EXECUTE(#Sqlstring)
E.g. let say GetDate() = 26 July 2019 and FirsDate = 1 July 2019 and #GCValue=10
Query Should return Difference of Days between above i.e. 26 July 2019 - (1 July 2019 + added 10 days so it became 11July2019) = 15 Days.

Whatever your reasons, here is a solution (not an elegant one :-) ) assuming SQL Server:
DECLARE #sqlstring VARCHAR(MAX);
DECLARE #GCValue varchar(10);
SET #GCValue = '10';
SET #sqlstring = 'SELECT Id, DATEDIFF(dd, getdate(), FirstDate + ' + #GCValue + ' ) from Table where Id=1234';
EXECUTE(#sqlstring);
You have to change #GCValue's data type to varchar (or explicictly convert it from int, as in cast(#GCValue as varchar(10)) to use it in string concatenation operations. And you can use DateDiff to compute the difference in days (dd parameter).

Related

SQL Server: import date in yyy-mm-dd from csv in dd-mmm-yy [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm receiving a csv with dates in a dd-mmm-yy format
05-SEP-19
I want to convert them into yyyy-mm-dd
2019-09-05
When I import the file with Microsoft Server Management Studio.
You can try this:
This converts string to date format, after this you can format date as you want...
DECLARE #String nvarchar(30);
SET #String = '05-SEP-19'
SELECT #String, CONVERT(date,substring(#String, 1, 2) + ' ' +
substring(#String, 4, 3) + ' ' +
substring(#String, 8, 4), 6)
Results:
05-SEP-19 2019-09-05
DECLARE #dt DATETIME = '05-SEP-19'
PRINT #dt
DECLARE #dts VARCHAR(20) = FORMAT(#dt, 'yyy-MM-dd')
PRINT #dts
gives
Sep 5 2019 12:00AM
2019-09-05
Completion time: 2019-11-22T11:16:43.8140327+02:00
Note that #dt has type DATETIME. What this piece of script does is (i) create DATETIME #dt initialised from a string containing an "acceptably recognisable" representation of a date (ii) display #dt default format (iii) create string initialised with custom-format of this value (iv) display that.
You have to distinguish between the (date) type and its formatted-for-display (string) representation.
DECLARE #Date VARCHAR(50)
SET #Date='05-SEP-19'
SELECT CONVERT(CHAR(10), CONVERT(DATETIME, #Date), 120) AS Date
Output
Date
-----
2019-09-05

How to format a wildcard query for dates in MS SQL?

I have a certain day range, let's say 8-01 to 8-08. I also have a database that has historical data from 1975-2014. Dates are formatted in yyyy-mm-dd form. So for example, today is 2014-08-06. How can I get historical records from 8-01 to 8-08 for all years? Keep in mind my date range might not span nicely across the same month. Another example would be 7/31 to 8/07.
Basically, I want to be able to do BETWEEN(%-8-01 AND %-8-08) where % is a wildcard. However, wildcards seem incompatible with date objects in MS SQL. Do I need to convert the dates to strings? What is the most efficient way of getting a generic month-day range independent of year?
Thanks.
This is a different approach than my other answer. It will make all dates have a year of 1900. Then you only need to take whatever is between your selected dates.
SELECT *
FROM Table1
WHERE DATEADD
(
year,
-DATEDIFF(year,'19000101',dateField),
dateField
) BETWEEN'19000801' AND'19000818'
You can extract the month and date part and compare those:
where
month(<yourdate>) = 8
and day(<yourdate>) between 1 and 8
Be aware that if you have an index on this column, you won't be using it this way.
The wildcard operator cannot be used in a BETWEEN statement. It's really only for LIKE statements. If you want to be able to modify your year, and that's it, you should pass it in as a parameter. The BETWEEN statement will take that with no problem.
DECLARE #StartMonth INT
DECLARE #Month INT
DECLARE #EndMonth INT
DECLARE #StartDay INT
DECLARE #Day INT
DECLARE #EndDay INT
SET #StartMonth = 8
SET #EndMonth = 8
SET #StartDay = 1
SET #EndDay = 8
IF #EndMonth > #StartMonth
BEGIN
#Month = #EndMonth
#StartMonth = #EndMonth
#EndMonth= #Month
END
IF #EndDay > #StartDay
BEGIN
#Day= #EndDay
#StartDay = #EndDay
#EndDay = #Day
END
SELECT *
FROM TABLE
WHERE MONTH(dateField) BETWEEN #StartMonthAND #EndMonth
AND DAY(dateField) BETWEEN #StartDay AND #EndDay

get last previous month records [duplicate]

This question already has answers here:
Get the records of last month in SQL server
(23 answers)
Closed 8 years ago.
sql 2005 server
get previous month records
Date product
24-05-2014 ball
25-05-2014 bat
01-06-2014 hat
i need
Date Product
24-05-2014 ball
25-05-2014 bat
declare #ex datetime
set #ex '06-01-2014'
select * from tabl where DATENAME(m,DATEADD(m,0,Date)) =DATENAME(m, DATEADD(m,0, #ex))- it works
select * from tabl where DATENAME(m,DATEADD(m,0,Date)) =DATENAME(m, DATEADD(m,-1,#ex))-not works
My sample code (tested on 2008). I don't know are YEAR and MOTH function in 2005 if not you need to use some string function to extract date / month part from datetime converted to string
declare #ex datetime = '2014-01-01'
declare #prev_year int
declare #prev_month int
set #prev_year = year(dateadd(month, -1, #ex))
set #prev_month = month(dateadd(month, -1, #ex))
select * from tabl
where year(Date) = #prev_year and month(Date) = #prev_month
You're using dd-MM-yyyy format for your dates, which is a varchar in SQL Server.
Therefor, you must use CONVERT :
declare #ex varchar(10)
set #ex = '06-01-2014'
SELECT DATENAME(m,DATEADD(m,0,GETDATE())),
DATENAME(m, DATEADD(m,-1,CONVERT(date, #ex, 103)));
This yields results:
June | May
I think you can figure out your solution from here.
Note: If you use declare #ex datetime , your results will yield June | December

convert string to datetime in sql server [duplicate]

This question already has answers here:
Convert varchar into datetime in SQL Server
(13 answers)
Closed 10 years ago.
I have a column of dates with no delimiters. The column is nvarchar. The strings are consistent in length and format of MMDDYYYY. How can I convert these values to datetime?
edit - this question is in reference to sql server.
Assuming SQL Server:
DECLARE #A NVARCHAR(10)
SET #A = '11302012'
SELECT CONVERT(DATETIME,LEFT(#A,2) + '/' +
SUBSTRING(#A,3,2) + '/' + RIGHT(#A,4),101)
BEGIN
DECLARE #d DATETIME
DECLARE #s NVARCHAR(32)
SET #s = N'12012013'
SET #d = SUBSTRING(#s, 5,4) + SUBSTRING(#s, 1,2) + SUBSTRING(#s, 3,2)
SELECT #d
END
You just have to mangle the string into a format SQL server can parse correctly into a date. In the above it's the YYYYMMDD format.
EDIT Removed "-"'s because French language settings break them.
First change the format to the one that always works no matter what server settings (YYYYMMDD) using two simple string functions, then convert to datetime:
declare #datestring varchar(8) = '11302012';
select CONVERT(datetime, RIGHT(#datestring, 4) + LEFT(#datestring, 4)) ConvertedDatetime;

NVARCHAR TO DATETIME conversion

I have a parameter that has a value of 14-Sep-2012 15:47:27 that I would like to update a table column with which is in 2012-08-10 05:00:00.000 format.
What would be the query needed '
#UpdateTime = '14-Sep-2012 15:47:27'
Update tbl
Set Datetimecol = CONVERT(datetime,#UpdateTime,110) ??
I am using SQL Server 2008. Thank you !
For the edited question, you only need to drop the 110 specification. There really isn't a specification for the format you have shown, but English installations of SQL Server will convert it.
e.g.
declare #UpdateTime datetime = '14-Sep-2012 15:47:27'
select CONVERT(datetime,#UpdateTime)
-- result
September, 14 2012 15:47:27
Assuming your month portion is at least 3 characters long, e.g. Mar, Marc, March, Sept, you can convert that very bad text datetime to a normal 3-char month format using the following
declare #updatetime nvarchar(20) = '18-Sept-2012'
declare #fixedtime nvarchar(20)
set #fixedtime = stuff(#updatetime,1,charindex('-',#updatetime),'')
set #fixedtime = Left(#updatetime,charindex('-',#updatetime))
+ stuff(#fixedtime,4,len(#fixedtime)-8,'')
-- #fixedtime contains `18-Sep-2012`
Update tbl
Set Datetimecol = #fixedtime
Yes, I deliberately left out the CAST/CONVERT in the update statement.
As long as your language settings are always English and your regional settings don't change, here is another approach (along with sample data of various potential formats):
DECLARE #x TABLE(y NVARCHAR(15));
INSERT #x VALUES('18-Sept-2012'),('9-May-2012'),('19-Oct-2012'),('04-March-2012');
SELECT z, CONVERT(DATETIME,z) FROM
(
SELECT SUBSTRING(y,s+1,3) + ' ' + LEFT(y,s-1) + ', ' + RIGHT(y,4) FROM
(
SELECT y, CHARINDEX('-',y) FROM #x
) AS y(y,s)
) AS z(z);
Results:
Sep 18, 2012 2012-09-18 00:00:00.000
May 9, 2012 2012-05-09 00:00:00.000
Oct 19, 2012 2012-10-19 00:00:00.000
Mar 04, 2012 2012-03-04 00:00:00.000
You can use the same calculation for a variable:
DECLARE
#y NVARCHAR(15) = N'18-Sept-2012',
#z DATETIME;
SELECT #z = CONVERT(DATETIME,z) FROM
(
SELECT SUBSTRING(y,s+1,3) + ' ' + LEFT(y,s-1) + ', ' + RIGHT(y,4) FROM
(
SELECT #y, CHARINDEX('-',#y)
) AS y(y,s)
) AS z(z);
SELECT #z;
-- UPDATE ...
(Now try with SET LANGUAGE FRENCH; and watch it all go to, well, somewhere.)
For this reason I highly recommend you stop storing / passing dates using the nvarchar type. We have strongly typed date/time types for a reason. When you need to pass a string literal, you should be using unambiguous, standard formats that aren't prone to differences in language, regional and dateformat settings. In this case the right format should be YYYYMMDD:
20120918
For more info, see:
Bad habits to kick : mis-handling date / range queries