SQL server stored procedure between statement - sql-server

I want to select from table where date with between
but problem is that in database there is not datetime column there is separated dateTime year, month and day
does it possible to create new variable inside stored procedure something like that?
checkin = new DateTime(year, month, day)
this year month and day are columns in datatable

You can convert string to DateTime using the function below:
convert(datetime, '02/15/2012', 101) -- mm/dd/yyyy

You could try something like:
-- dateadd formula borrowed from
-- http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx
with includeDate as (
select column1,
column2,
column3,
dateadd(month,(([year]-1900)*12)+[month]-1,[day]-1) as date
from yourTable
)
select *
from includeDate
where date between #startDate and #endDate

Of course in your stored procedure, you would populate the query with the values from your table, the code below is an example of converting the separate date fields into one datetime value.
I don't know the data type of your day, month and year fields but the following should work if you have an int value:
declare #day int
declare #month int
declare #year int
declare #fulldate smalldatetime
set #day = '1'
set #month = '9'
set #year = '2012'
SELECT #fulldate = Convert(smalldatetime, Cast(#month as varchar(2)) + '/'
+ Cast(#day as varchar(2)) + '/' + Cast(#year as varchar(4)), 101)
select Convert(varchar(10), #fulldate, 101)
If the values are stored as a string:
declare #day varchar(2)
declare #month varchar(2)
declare #year varchar(4)
declare #fulldate smalldatetime
set #day = '1'
set #month = '9'
set #year = '2012'
SELECT #fulldate = Convert(smalldatetime, #month + '/'
+ #day + '/' + #year, 101)
select Convert(varchar(10), #fulldate, 101)

Related

Creating a datetime with year and month as inputs

I want to create a datetime with a value like:
2019-09-01 00:00:00.000
I have the values for year and month in variables #year and #month.
What is the best way to create a datetime with inputs?
I would use DATEFROMPARTS.
declare #year int = 2019
, #month int = 9
SELECT convert(datetime, DATEFROMPARTS(#year, #month, 1))
I'm include a #Day part too, as you may find it useful. If you do not want it, replace RIGHT('00' + LTRIM(#Day),2) with '01'
DECLARE #Year VARCHAR(4) = '2019';
DECLARE #Month VARCHAR(2) = '09'
DECLARE #Day VARCHAR(2) = '01'
SELECT CAST(CAST(#Year as char(4))
+ RIGHT('00' + LTRIM(#Month),2)
+ RIGHT('00' + LTRIM(#Day),2)
AS Datetime)

How to get days from date to date in SQL Server?

In SQL Server, I want to get days from date to date. Example: from 2015/12/28 to 2016/01/02, the result as
2015/12/28
2015/12/29
2015/12/30
2015/12/31
2016/01/01
2016/01/02
DECLARE #STARTDATE DATETIME = '2015-12-28'
DECLARE #ENDDATE DATETIME = '2016-01-02'
SELECT BETWEEN #STARTDATE AND #ENDDATE AS DAYS
Use CTE
DECLARE #STARTDATE DATE = '2015-12-28'
DECLARE #ENDDATE DATE = '2016-01-02'
;WITH CTE AS
(
SELECT #STARTDATE As dt
UNION ALL
SELECT DATEADD(D,1,dt) AS dt
FROM CTE
WHERE dt < #ENDDATE
)
SELECT * FROM CTE
You could build a calendar table, which would probably come in handy down the road. Or you could use a loop.
DECLARE #ENDDATE DATETIME = '2016-01-02'
DECLARE #DAY DATETIME = '2015-12-28'
WHILE #Day <= #ENDDATE
BEGIN
SELECT #DAY
SET #DAY = DATEADD(DD,1,#DAY)
END
Or for all of the days in one result set:
DECLARE #ENDDATE DATETIME = '2016-01-02'
DECLARE #DAY DATETIME = '2015-12-28'
DECLARE #TABLE TABLE (DATE DATETIME)
WHILE #Day <= #ENDDATE
BEGIN
INSERT #TABLE
VALUES (#DAY)
SET #DAY = DATEADD(DD,1,#DAY)
END
SELECT *
FROM #TABLE
You can specify the dates in your WHERE clause. For example, WHERE date >=#STARTDATE AND date <=#ENDDATE. That should return the full date in your results.
using Numbers table
select dateadd(day,n,startdate)
from numbers
where dateadd(day,n,startdate)<=enddate
order by n

SQL select between dates, but show all when start and end date are empty

In SQL, I can use wildcard '%' on string and Select statement will show all the records like
select * from tablea where title like '%'
My question is what if both the start and end date are empty in the BETWEEN & AND function in Select statement.
Example
`select * from table where inputdate between '2014-01-01'` and '2014-01-31'
It works fine in this statement because there are start and end date.
What if there isn't any start and end date, and I want to show all the records?
select * from table where inputdate between '%' and '%' <--- not working.
Many thanks.
You can write your query in a way that inputdate column is evaluated against the value passed or if the no value is passed to #StartDate variable just pick earliest possible date,
I have select 1900-01-01 as the earliest date but depending on your column type you can pick a more appropriate substitute start and end dates.
DECLARE #StartDate DATE = '2014-01-01'
DECLARE #EndDate DATE = '2014-01-31'
select * from table
where inputdate >= COALESCE(#StartDate, '19000101')
and inputdate <= COALESCE(#EndDate , '99991231')
Dynamic SQL
Another better way of handling this kind of query with optional parameters will be using dynamic sql something like this...
DECLARE #StartDate DATE = '2014-01-01'
DECLARE #EndDate DATE = '2014-01-31'
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N'SELECT * FROM Table 1 = 1 '
+ CASE WHEN #StartDate IS NOT NULL THEN
N' AND inputdate >= #StartDate ' ELSE N' ' END
+ CASE WHEN #EndDate IS NOT NULL THEN
N' AND inputdate <= #EndDate ' ELSE N' ' END
Execute sp_executesql #Sql
,N'#StartDate DATE, #EndDate DATE'
,#StartDate
,#EndDate
wildcard can only be used on string, But since you mentioned the column is Date, you can do something better. Date min/max has been defined in almost all DBMS, IDK about the max but the min is usually January 1, 1753. so you can try between ' January 1, 1753' and 'date max'
SELECT * FROM table t
WHERE t.Date >= IIF(#FromDate IS NULL, t.Date, #FromDate)
AND t.Date <= IIF(#ToDate IS NULL, t.Date, #ToDate)
works fine.

converting date time format in sql

i have a stored procedure like this:
ALTER procedure [dbo].[startandenddtime]
#startdate nvarchar(100)
as begin
declare #date3 nvarchar(100) = cast(CONVERT(varchar(100), #startdate + ' 16:59:59', 120) as datetime)
select date3 as startdate
end
If i pass my startdate as 2013-05-08 i am getting out put as :
but i want to get out put as 2013-05-08 16:59:59.000..so how i can convert this format
is this date time i can store in nvarchar varibale
Try like this
DECLARE #StartDate NVARCHAR(100)='2013-05-08'
SELECT CONVERT(VARCHAR,#StartDate+'16:59:59', 121)
MORE
SQL Fiddle
try this
ALTER procedure [dbo].[startandenddtime]
#startdate nvarchar(100)
as begin
declare #date3 nvarchar(100) = cast(CONVERT(VARCHAR(24),#startdate ,121)) as datetime)
select date3 as startdate
end
For more in details see this, http://technet.microsoft.com/en-us/library/ms187928.aspx
try this
Select cast(CONVERT(varchar(100), #startdate + ' 16:59:59') as date)
Or
Select cast(CONVERT(varchar(100), #startdate + ' 16:59:59') as datetime)
Try this :
Declare #dt varchar(20);
Declare #startdate varchar(20)='2013-05-08';
SET #dt= CONVERT(VARCHAR(20), CONVERT(datetime,#startdate+' 16:59:59'), 100)
Select #dt;
Just don't cast varchar value to datetime
edit: If you don't get what i meant in my comment:
convert(varchar, convert(datetime, #startdate + ' 16:59:59', 120), 120)

sql stored procedure execute command

I've created the following stored procedure on sql:
CREATE PROCEDURE Sp_generate_report (#YEAR INT,
#MONTH INT)
AS
DECLARE #CATEGORY VARCHAR(20)
DECLARE #BEGIN_DATE DATE
DECLARE #END_DATE DATE
BEGIN
SELECT #BEGIN_DATE = Cast(( Cast(#YEAR AS VARCHAR) + '-'
+ Cast(#MONTH AS VARCHAR) + '-' + '1' ) AS DATE)
SELECT #END_DATE = Cast(( Cast(#YEAR AS VARCHAR) + '-' +
Cast(#MONTH AS VARCHAR) + '-' + '32' ) AS DATE)
SELECT TOP 1 #CATEGORY = Name
FROM dbo.Profitible_categories(#BEGIN_DATE, #END_DATE)
INSERT INTO dbo.MONTHLY_SUMMARY_REPORTS
VALUES (#CATEGORY)
END
The procedure was created successfully, but when I try to execute it with the following command:
EXECUTE SP_GENERATE_REPORT 2012, 7
I get this error message:
Msg 241, Level 16, State 1, Procedure SP_GENERATE_REPORT, Line 8
Conversion failed when converting date and/or time from character
string.
thanks in advance for the help.
You can calculate the last day of the month without all that nasty string concatenation or trying to guess which month it is and pick the last day.
CREATE PROCEDURE dbo.Sp_generate_report
#YEAR INT,
#MONTH INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #BEGIN_DATE DATE = DATEADD(MONTH, #MONTH-1, CONVERT(DATE,
CONVERT(CHAR(4), YEAR) + '0101'));
DECLARE #END_DATE DATE = DATEADD(DAY, -1, DATEADD(MONTH, 1, #BEGIN_DATE));
INSERT INTO dbo.MONTHLY_SUMMARY_REPORTS
SELECT TOP (1) Name
FROM dbo.Profitible_categories(#BEGIN_DATE, #END_DATE);
END
GO

Resources