Datetime syntax error - sql

I'm newbie at SQL Server. I'm stuck on a problem that I can't solve. I want to write a stored procedure.
TimeStamp column's datatype is datetime.
This my stored procedure:
#fetchtype int,
#startdate nvarchar(22),
#finishdate nvarchar(22)
AS
if (#fetchtype = 0)
BEGIN
PRINT('Select TimeStamp ' From WindData Where TimeStamp between '+#startdate+' and '+#finishdate)
EXEC('Select TimeStamp ' From WindData Where TimeStamp between '+#startdate+' and '+#finishdate)
END
An also my execution query is
DECLARE #return_value int
EXEC #return_value = [dbo].[Get_Values]
#columnnames = N'V81_Avg',
#fetchtype = 0,
#startdate = N'2013-04-23 12:58:40.000',
#finishdate = N'2013-04-23 12:59:00.000'
SELECT 'Return Value' = #return_value
But when I execute my query I get this error
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '12'.
I think I didn't write properly datetime format.

The problem here is in SQL query string:
It should be:
PRINT('Select TimeStamp From WindData Where TimeStamp between '''+#startdate+''' and '''+#finishdate+'''');
EXEC('Select TimeStamp From WindData Where TimeStamp between '''+#startdate+''' and '''+#finishdate+'''')
But the best way is to use these parameters as DATETIME and avoid dynamic query and replace EXEC() with just SELECT:
#startdate datetime,
#finishdate datetime
...
Select TimeStamp From WindData Where TimeStamp between #startdate and #finishdate;
...

You need to put quotes around the dates:
declare #sql nvarchar(max) = 'Select TimeStamp From WindData Where TimeStamp between '''+#startdate+''' and '''+#finishdate+'''')
EXEC(#sql);
Or, better yet, use sp_executesql:
declare #sql nvarchar(max) = 'Select TimeStamp From WindData Where TimeStamp between #startdate and #finishdate')
exec sp_executesql #sql, N'#startdate date, #finishdate date', #startdate = #startdate, #finishdate = #finishdate;

CREATE PROC yourSPName
(#fetchtype int,
#startdate nvarchar(22),
#finishdate nvarchar(22)
)
AS
DECLARE #sqlstr varchar(2500)
if (#fetchtype = 0)
BEGIN
Select TimeStamp From WindData Where TimeStamp between convert(datetime,#startdate) and convert(datetime,#finishdate)
END

Related

SQL Server: fetching a variable name from a table and assigning value inside the stored procedure

I have some variable name stored in a table, which I need to populate in a stored procedure based on a condition.
For example:
Query: select column1 from TestTable
Output of Query: #FromDate
Now inside the stored procedure, I have the following:
DECLARE #FromDate DATE = '2022-06-01'
DECLARE #QueryResult Varchar(50);
DECLARE #SQLCommand Varchar(50);
SELECT #QueryResult = column1
FROM TestTable
SET #SQLCommand = 'SELECT * FROM emp WHERE joindate >= ''' + #QueryResult + ''';'
EXEC (#SQLCommand);
Now I am expecting that result should be all the employee whose joindate >= '2022-06-01'. Or in other words, I am expecting to use #FromDate variable to fetch data. But when i run query, I get the following error:
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#FromDate"
When I run:
print #SQLCommand;
I get:
select * from emp where joindate >= '#FromDate';
While I am expecting that #FromDate value should be populated here at run time.
Will be thankful for any help regarding this.
Update: actually, there is a loop inside my sp, which fetches the data from table (data contains variable names to be used in the stored procedure in different logic I) like for a particular record: I need to add 20 days in #fromdate, and for another record I need to add 30 days. Now when my loop will run, it will fetch either dateadd(day, 20, #fromdate) or dateadd(day, 30, #fromdate) from table based on where clause and then I need to fill in the value of #fromdate (this is parametrise variable) and fetch the results accordingly.
Update 2:
Please see below my code
USE [GBI_archive]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_Process_Data]
(#StartDate DATE = NULL,
#EndDate DATE = NULL)
AS
DECLARE #FromDate DATE = ISNULL(#StartDate, DATEADD(DAY, 1, EOMONTH(GETDATE(), -1)));
DECLARE #ToDate DATE = ISNULL(#EndDate, GETDATE());
DECLARE #CalculationMethodFromDate VARCHAR(255);
DECLARE #SelectStatement VARCHAR(255);
DECLARE #TableIntoStatement VARCHAR(255);
DECLARE #FromStatement VARCHAR(255);
DECLARE #SQLCommand VARCHAR(255);
DECLARE cursor_product CURSOR FOR
SELECT calculation_method_from_date
FROM [dbo].[Calculation_Method_Configuration];
-- Here output can be DATEADD(DAY, -6, #FromDate) or DATEADD(DAY, -14, #FromDate) or so on
OPEN cursor_product;
FETCH NEXT FROM cursor_product INTO #CalculationMethodFromDate
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT #CalculationMethodFromDate
SET #SelectStatement = 'SELECT CURRENT_TIMESTAMP, * ';
SET #TableIntoStatement = 'INTO [dbo].[Table_For_Function_Output]';
SET #FromStatement = 'FROM [dbo].[EmployeeData] where joindate >= ''' + #CalculationMethodFromDate + ''';'
-- SET #SQLCommand = concat (#SelectStatement , ' ', #TableIntoStatement , ' ', #FromStatement);
PRINT #SQLCommand;
EXEC (#SQLCommand);
FETCH NEXT FROM cursor_product INTO #CalculationMethodFromDate,
END;
CLOSE cursor_product;
DEALLOCATE cursor_product;
GO
Now for anyone iteration of loop, print #SQLCommand shows this (if #CalculationMethodFromDate = 'DATEADD(DAY, -6, #FromDate)') :
SELECT CURRENT_TIMESTAMP, * INTO [dbo].[Table_For_Function_Output] FROM [dbo].[EmployeeData] where joindate >= 'DATEADD(DAY, -6, #FromDate)';
and exec command throws this error:
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#FromDate"
But if I am passing #FromDate = '2022-06-07' as parameter to this sp, my expectations for print #SQLCommand shows is:
SELECT CURRENT_TIMESTAMP, * INTO [dbo].[Table_For_Function_Output] FROM [dbo].[EmployeeData] where joindate >= '2022-06-01';
In short: #FromDate variable coming from database at runtime, should be assigned a value from stored procedure.
You don't need a cursor here, you just need to build one big UNION ALL statement. And you need to pass the #FromDate and #ToDate into the dynamic SQL.
CREATE OR ALTER PROCEDURE [dbo].[sp_Process_Data]
#StartDate DATE = NULL,
#EndDate DATE = NULL
AS
DECLARE #FromDate DATE = ISNULL(#StartDate, DATEADD(DAY, 1, EOMONTH(GETDATE(), -1)));
DECLARE #ToDate DATE = ISNULL(#EndDate, GETDATE());
DECLARE SQLCommand nvarchar(max) = (
SELECT STRING_AGG(N'
SELECT CURRENT_TIMESTAMP, e.*
FROM dbo.EmployeeData e
where e.joindate >= ' + CAST(cm.calculation_method_from_date AS nvarchar(max))
, '
UNION ALL ')
FROM dbo.Calculation_Method_Configuration cm
);
PRINT #SQLCommand;
EXEC sp_executesql
#SQLCommand,
N'#FromDate DATE, #ToDate DATE',
#FromDate = #FromDate,
#ToDate = #ToDate;
go
The design itself is questionable. You should really just have a column which tells you how many days to add, then you can just do
SELECT CURRENT_TIMESTAMP, e.*
FROM dbo.EmployeeData e
JOIN dbo.Calculation_Method_Configuration cm
ON e.joindate >= DATEADD(day, -cm.days, #FromDate);
well actually you could simply use sp_executesql for this.
Simplified sample:
-- demo table:
SELECT DATEADD(day, -7, GETDATE()) [Date] INTO [#demo] UNION ALL SELECT DATEADD(day, 1, GETDATE());
-- demo:
DECLARE #CalculationMethodFromDate NVARCHAR(MAX) = N'DATEADD(DAY, -6, #FromDate)';
DECLARE #FromDate DATE = GETDATE();
DECLARE #SQL NVARCHAR(MAX) = N'SELECT * FROM [#demo] WHERE [Date] >= '+#CalculationMethodFromDate+N';';
EXEC sp_executesql #SQL, N'#FromDate DATE', #FromDate=#FromDate;
--cleanup
drop table [#demo];

Dates returned as columns in SQL Select

My user will submit a FromDate and a ToDate. What I want to happen is to select the dates that fall in between these dates, which I have accomplished with the script below. The dates will by dynamic.
DECLARE #fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE #toDateParam DATETIME = '2022-01-29 00:00:00.000'
;WITH fnDateNow(DayOfDate) AS
(
SELECT #fromDateParam AS TransactionDate
UNION ALL
SELECT DayOfDate + 1
FROM fnDateNow
WHERE DayOfDate < #toDateParam
)
SELECT fnDateNow.DayOfDate AS TransactionDate
FROM fnDateNow
This returns that dates as rows. What I am looking for is a way to make these dates return as the columns for a different script.
This table is called DailyTransactionHeader and it has a column [TransactionDate] and another one called [Amount].
There is the probability that their is not a DailyTransactionHeader with the specified Date for this I am looking to return 0.
So I am trying to have the data look like this (I formatted the date) There would be more than one row, but I just wanted to show an example of what I am trying to accomplish.
I appreciate any help,
Thanks
You can do it using dynamic sql. For example:
CREATE PROCEDURE [GET_DATE_TABLE]
(
#FROMDATE DATETIME,
#TODATE DATETIME
)
AS
DECLARE #PDATE DATETIME
DECLARE #SQL VARCHAR(MAX)
DECLARE #SEP VARCHAR(10)
SET #PDATE = #FROMDATE
SET #SQL = 'SELECT '
SET #SEP = ''
WHILE #PDATE < #TODATE
BEGIN
SET #SQL = #SQL + #SEP + 'NULL as [' + CONVERT(VARCHAR, CONVERT(DATE, #PDATE)) + ']'
SET #PDATE = #PDATE + 1
SET #SEP = ', '
END;
EXEC(#SQL)
Test Example:
DECLARE #fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE #toDateParam DATETIME = '2022-01-29 00:00:00.000'
exec dbo.GET_DATE_TABLE #fromDateParam, #toDateParam

Conversion failed when converting date and/or time from character string in sql server

I have a function to convert a string to datetime (101) format.
But it gives me an error when I convert this value.
2016-03-01 00:00:00.0000000
And the error is
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
And my function is ..
ALTER FUNCTION [dbo].[ConvertToDate]
(
#Value nVarchar(MAX)
)
RETURNS DATETIME
AS
BEGIN
IF (#Value <> NULL OR #Value <> '')
BEGIN
DECLARE #dt DATETIME
SET #dt = CONVERT(DATETIME,#Value,101)
--SET #dt = CAST(#Value AS DATETIME(101))
RETURN #dt
END
RETURN NULL
END
What is the problem?
It is problem your data. It is not converting.
Your data should be like this
'2016-03-01 00:00:00.0000000'
But you can change your data like this
'2016-03-01 00:00:00.000'
Too many zeros in the millisecond part. This works fine
DECLARE #Value nVarchar(MAX)='2016-03-01 00:00:00.000'
SELECT CONVERT(DATETIME,#Value,101)
You can try using LEFT like this
DECLARE #Value nVarchar(MAX)='2016-03-01 00:00:00.000000'
SELECT CONVERT(DATETIME,LEFT(#Value,23),101)
DECLARE #dt VARCHAR(50) ='2016-03-01 00:00:00.000000'
select CAST (#dt AS DATETIME2)

SQL Custom datetime format to datetime

I have a varchar which is coming through as the following format: yyyy-dd-MM hh:mm:ss
I need to be able to convert that to a valid datetime, what will be the best method?
Edit for example:
DECLARE #d varchar = '2014-17-01 12:00:00'
SELECT CONVERT(DATETIME, #d, 103);
returns
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
Via CONVERT?
SELECT CONVERT(DATETIME, '2014-31-01 17:00:00', 103 /* British */);
(No column name)
2014-01-31 17:00:00.000
You can use CONVERT as:
DECLARE #TodayDate datetime
SET #TodayDate = GETDATE()
SELECT CONVERT(VARCHAR, #TodayDate, 110) AS TodayDate
Output:
07-04-2014
Hope it helps !
EDITED to add SET DATEFORMAT. This resolved the error for me and ensures everything gets into the correct bucket.
SET DATEFORMAT ydm
DECLARE #d VARCHAR(20) = '2014-17-01 12:00:00';
DECLARE #targetDate DATETIME = GETDATE(); -- Control Date
DECLARE #passedDate DATETIME = CAST(#d AS DATETIME);
SELECT #targetDate, #passedDate;
Try to interchange day and month and then PARSE new string to datetime.
DECLARE #d varchar(50) = '2014-17-01 12:00:00'
DECLARE #year varchar(10) = SUBSTRING(#d,1,4)
DECLARE #day varchar(10) = SUBSTRING(#d,6,2)
DECLARE #month varchar(10) = SUBSTRING(#d,9,2)
DECLARE #time varchar(10) = SUBSTRING(#d,12,8)
DECLARE #new_d varchar(50) = #year+'-'+#month+'-'+#day+' '+#time
SELECT PARSE(#new_d AS datetime USING 'en-US') as Result

How do I select any value from SP?

I have SP like :
CREATE PROCEDURE MySP
(
#startdate datetime = null,
#enddate datetime = null
)
AS
BEGIN
declare #date datetime
Set #date= convert(datetime,convert(varchar(10),getdate(),101))
SET #startdate = ISNULL(#startdate,convert (datetime,convert(varchar(10),getdate(),101)))
select #startdate -- i want to select and view this value
END
GO
I want to view select #startdate value, How can i do this?
You execute the stored procedure.
exec MySP
Result:
(No column name)
2011-08-10 00:00:00.000
Edit
Stored procedure with output parameter #startdate
alter PROCEDURE MySP
(
#startdate datetime = null out,
#enddate datetime = null
)
AS
BEGIN
declare #date datetime
Set #date= convert(datetime,convert(varchar(10),getdate(),101))
SET #startdate = ISNULL(#startdate,convert (datetime,convert(varchar(10),getdate(),101)))
END
Use like this
declare #D datetime
exec MySP #D out
select #D