hey guys,
i want to convert datetime from string, i have string which contains 'GETDATE' now i want to convert the same in datetime, the string in sql server is been defined as varchar(max)
Please reply how can i type cast the GETDATE() function from string to datetieme.
Regards
Abbas Electricwala
I guess that you mean that you have a string that contains the text GetDate() like this.
declare #S varchar(50)
set #S = 'getdate()'
And you want to turn that into a date variable executing getdate().
You could do this since you know what what getdate() means.
declare #S varchar(50)
set #S = 'getdate()'
declare #D datetime
set #D = (select
case #S when 'getdate()'
then getdate()
else null
end)
Does not really make sense, there probably is more to this than you are telling.
If you have just date string you can do it like this:
SELECT CONVERT(DATETIME, '2009-02-25 15:31:17.888')
But... GETDATE() returns a datetime value, not a string value. Just assign the GETDATE() result to your variable.
Sample (may be inacurate):
declare #mydate as datetime
set #mydate = GETDATE()
Related
I am trying to create a function that converts a given date string to the desired DateTime format.
The code is:
Alter function dbo.getDateValue1(#inputdate varchar)
returns varchar
as
begin
declare #inputDateTransformed datetime = CAST(#inputdate AS datetime2)
declare #setDatevalue varchar = convert(varchar,#inputDateTransformed ,112)
return #setDatevalue
end
And I am calling the function as below:
SELECT dbo.getDateValue1('2022-01-01 18:15:15.600' )
Which gives me the error:
Conversion failed when converting date and/or time from character string.
Any help would be appreciated.
Sample:
Create function [dbo].[getDateValue1](#input_date datetime2)
returns varchar(100)
begin
declare
#v_ret varchar(100)
set #v_ret = CONVERT(varchar, #input_date, 112)
return #v_ret
end
SELECT dbo.getDateValue1('2022-01-01 18:15:15.600')
-- Result:
20220101
I have the following query:
DECLARE #Month int
DECLARE #Year int
set #Month = 2
set #Year = 2004
Declare #MonthStartDate datetime
declare #MonthEndDate datetime
set #MonthStartDate = 'select DATEADD(month,#Month-1,DATEADD(year,#Year-1900,0))'
set #MonthEndDate = 'select DATEADD(day,-1,DATEADD(month,#Month,DATEADD(year,#Year-1900,0)))'
return #MonthStartDate , #MonthEndDate
But it returns:
"Conversion failed when converting date and/or time from character string."
What's wrong here?
Alternatively, you can also use as follow..
select #MonthStartDate = DATEADD(month,#Month-1,DATEADD(year,#Year-1900,0))
select #MonthEndDate = DATEADD(day,-1,DATEADD(month,#Month,DATEADD(year,#Year-1900,0)))
You should use DateTime expression instead of string literal. Just remove quotes:
DECLARE #Month int
DECLARE #Year int
set #Month = 2
set #Year = 2004
Declare #MonthStartDate datetime
declare #MonthEndDate datetime
set #MonthStartDate = DATEADD(month,#Month-1,DATEADD(year,#Year-1900,0))
set #MonthEndDate = DATEADD(day,-1,DATEADD(month,#Month,DATEADD(year,#Year-1900,0)))
Looking at your Query (Since you don't have enough Description on the Question ) What I understood is that you are trying to get the First and Last day of a Given month. If you are using a SQL Server Version 2012 or Above, then you have an Inbuild Function called EOMONTH() which can be used to calculate the End of any given month. Otherwise, you may try the below method on any Version on SQL Server
Declare #MonthStartDate datetime,
#MonthEndDate datetime,
#Year int,
#Month int --It's Better to Declare all the variables in the same space for easy handling
SELECT
#Month = 2,
#Year = 2004 -- Common Assignments can be done together
;WITH MNT
AS
(
SELECT
MonthStartDate = CAST(#Month AS VARCHAR(20))+'/01/'+CAST(#Year AS VARCHAR(20)) -- Hardcoded Day as 1 since Month Start always at 1
)
SELECT
#MonthStartDate = MonthStartDate,
#MonthEndDate = DATEADD(DAY,-1,DATEADD(MONTH,1,MonthStartDate))
FROM MNT
I am trying to create dynamic code for date calculation in SQL stored procedures but am having problems executing string expressions and parameters as date expressions.
I want to hold generic string expressions in a table that will create the dates according to the value of the parameters.
for example this is a generic expression :
DATEADD(#TimeResolution, -#IterationN, #CurrentCalc)
as you can see these generic expressions are composed out of parameters to.
in the stored procedures I intend to declare the variables that are in the expression and assign values to them using a select statement from a different table.
the problem is that after deriving these string values and writing the expression it does not give me the date I want but fails.
so for example if I write the following code
declare #Today date
declare #LastYear date
set #Today = getdate()
set #LastYear = DATEADD(year, -1, #Today)
select #Lastyear
it works fine and I will get last year's date.
but when I try something like this :
declare #Today date
declare #LastYear date
declare #Timeresolution varchar(5)
select #Timeresolution = [Timeresolution] from dbo.mytable where rule_id=1//Timeresolution is a varchar column in my table holding the values 'year' or 'month'
declare Iteration int
select #Iteration = [Iteration] from dbo.mytable where rule_id=1 //Iteration is a int column in my table holding the values 1 or 2, or 3
set #Today = getdate()
set #LastYear = DATEADD(Timeresolution , -Iteration , #Today)
select #Lastyear
this gives me a conversion error.
Is there a way to create such dynamic date expressions?
It isn't possible to use a variable for the interval in DATEADD, but you can do something like this:
IF #Timeresolution = 'year'
BEGIN
SET #LastYear = DATEADD(year, -#Iteration , #Today)
END
IF #Timeresolution = 'month'
BEGIN
SET #LastYear = DATEADD(month, -#Iteration , #Today)
END
The code select DATEPART(month,getutcdate()) returns an integer representing the numeric month value of the current date.
The value MONTH is one of a number of predefined options for the interval parameter.
What is the underlying data type of that interval value?
declare #date datetime = getutcdate()
, #interval notNVarChar(16) = 'month' --what type should this be?
--Would it need quotes for assignment?
select DATEPART(#interval, #date)
You can make it parameterize by making a dynamic SQL as below:
declare #date datetime
set #date = GETDATE()
declare #option varchar(50)
declare #sql varchar(max)
SET #option = 'MONTH' --Here you can set other options like hour, second, milisecond etc..
set #sql = 'SELECT DATEPART('+ #option + ',''' + CONVERT(varchar,#date,21)+''')'
print #sql
EXEC( #sql)
There isn't one - you cannot parameterize it.
From the documentation:
DATEPART ( datepart , date )
datepart
Is the part of date (a date or time value) for which an integer will be returned. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid.
(my emphasis)
There are lots of options available like :
day
week
hour
minute
second
millisecond
etc..
PLease go thru thisLINK
I tried to figure out a dynamic query to get date col within past 20 days. The idea is quite simple and, moreover, I know the table does contain dates from getdate() to -20 days but still no result get returned
DECLARE #date_past_period varchar(MAX);
DECLARE #date_past_number varchar(MAX);
SET #date_past_period='day';
SET #date_past_number='20';
DECLARE #aDate datetime;
DECLARE #sql varchar(MAX);
SET #sql='SELECT date FROM table WHERE convert(varchar,date,121) BETWEEN convert(varchar,getdate(),121) AND convert(varchar,dateadd('+#date_past_period+', -'+#date_past_number+', getdate()),121)';
exec(#sql);
Maybe the problem is in dynamic thing but I am not sure.
Any useful comment is appreciated
You can use CASE function (T-SQL):
CREATE PROCEDURE MyStoredProcedure
#IntervalType VARCHAR(15),
#Num INT
AS
DECLARE #StartDate DATETIME = GETDATE();
DECLARE #EndDate DATETIME =
CASE #IntervalType
WHEN 'DAY' THEN DATEADD(DAY,#Num,#StartDate)
WHEN 'MONTH' THEN DATEADD(MONTH,#Num,#StartDate)
WHEN 'YEAR' THEN DATEADD(YEAR,#Num,#StartDate)
END;
IF #EndDate IS NULL
RAISERROR('Invalid params', 16, 1);
ELSE
SELECT date FROM table WHERE date BETWEEN #StartDate AND #EndDate;
By converting to VARCHAR your search condition from WHERE will not be SARG ( 1 & 2 ).
I am pretty sure this scenario can be covered without using dynamic SQL, however, one obvious problem in your SQL is the between clause - the range is in the wrong order. Try changing your #sql as below:
SET #sql='SELECT date FROM table WHERE convert(varchar,date,121) BETWEEN convert(varchar,dateadd('+#date_past_period+', -'+#date_past_number+', getdate()),121) AND convert(varchar,getdate(),121)';