Convert datetime to yyyymmddhhmmss in sql server - sql

I need to calculate the local time from yyyymmddhhmmss and return it as yyyymmddhhmmss. I have tried the below, it is working but I am not able to get rid of the month name.
Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
Declare #VarCharDate2 varchar(max)
--Declare
set #VarCharDate = '20131020215735' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' + SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2) + ' ' + SUBSTRING(#VarCharDate,9,2) +':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
--Convert to Date and Add offset
set #VarCharDate2 = DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),CONVERT(DATETIME,#VarCharDate1,20))
select #VarCharDate2
-- Now we need to revert it to YYYYMMDDhhmmss
--Tried this but month name still coming
Select convert(datetime, #VarCharDate2, 120)

Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
Declare #VarCharDate2 datetime
--Declare
set #VarCharDate = '20131020215735' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' + SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2) + ' ' + SUBSTRING(#VarCharDate,9,2) +':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
--Convert to Date and Add offset
set #VarCharDate2 = DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),CONVERT(DATETIME,#VarCharDate1,120))
select #VarCharDate2
-- Now we need to revert it to YYYYMMDDhhmmss
--Tried this but month name still coming
Select convert(datetime, #VarCharDate2, 120)
by using datetime data type you will always have the correct datetime

DECLARE #VarcharDate VARCHAR(14)
DECLARE #VarcharDateWorker VARCHAR(19)
DECLARE #VarcharDateResult VARCHAR(19)
--DECLARE
SET #VarcharDate = '20131020215735' --- YYYYMMDDHHMMSS
SELECT #VarcharDate AS [InputValue]
--Convert String to date format. Adding trailing space to ensure STUFF can validate the string (Length 19 else NULL)
SET #VarcharDateWorker = STUFF(STUFF(STUFF(STUFF(STUFF(STUFF(#VarcharDate+' ',5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':'),20,0,'')
SELECT #VarcharDateWorker AS [TransformStage1]
--Check if date is valid (Return Null if date is invalid)
SET #VarcharDateWorker = CASE WHEN ISDATE(#VarcharDateWorker) = 1 THEN #VarcharDateWorker ELSE NULL END
SELECT #VarcharDateWorker AS [TransformStage2]
--Convert to Date and Add offset
SET #VarcharDateWorker = CONVERT(VARCHAR(19),DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),#VarcharDateWorker),120)
SELECT #VarcharDateWorker AS [TransformStage3]
--Cleanout Special Characters to get YYYYMMDDHHMMSS format
SET #VarcharDateResult = REPLACE(REPLACE(REPLACE(#VarcharDateWorker, ' ', ''), '-', ''), ':', '')
SELECT #VarcharDateResult AS [OutputValue]
I think when dealing with Date columns, we need to also be compensating for bad data. Added additional Validation Steps and cleaned-up code

Try this -
Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
Declare #VarCharDate2 varchar(max)
--Declare
set #VarCharDate = '20131020215735' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' + SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2) + ' ' + SUBSTRING(#VarCharDate,9,2) +':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
--Convert to Date and Add offset
set #VarCharDate2 = DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),CONVERT(DATETIME,#VarCharDate1,20))
select #VarCharDate2
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, #VarCharDate2, 112), 126), '-', ''), 'T', ''), ':', '') [date]
It will return -
date
20131021035700

Related

Error when converting dynamic offset and datetime

I have a dynamic parameter for offset and datetime.
And I have problem when converting the date.
Declare #STR NVARCHAR (MAX)
Declare #offset nvarchar = '+05:00'
Declare #paramrequest date = '2017-03-30'
SET #STR = 'select .... where '
+ CONVERT(DATE, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, + 'REQUESTDATETIME'), #offset )) + ' >=' + CAST(#paramrequest AS DATE);
EXECUTE (#STR)
When I run the script, it gets me this error. How to get fix this error?
Conversion failed when converting date and/or time from character string.
You need to build your string correctly. use CONCAT like this:
SET #STR = CONCAT('select .... where ',
'CONVERT(DATE, SWITCHOFFSET(CONVERT(DATETIMEOFFSET,',
'REQUESTDATETIME),''',
#offset,''' )) >= ''',
CAST(#paramrequest AS DATE), '''')

Comma seperated values to SQL IN STATEMENT

If i have a comma separated list of values:
A1,B2,B3
How do i pass this into a variable and then form it into an SQL IN statement.
DECLARE #DATE AS VARCHAR(50)
SELECT #DATE = CONVERT(VARCHAR(8), Getdate(), 112)
--PRINT #DATE
DECLARE #TIME AS VARCHAR(50)
--PRINT TIME
SELECT #TIME = Replace(CONVERT(VARCHAR(5), Getdate(), 108), ':', '')
DECLARE #ID AS VARCHAR(50)
SELECT #ID = Replace(W0128001, 32322, 32323, 3232323, 2323232, ',', ',')
--PRINT #ID
DECLARE #QUERY NVARCHAR(MAX);
SET #QUERY = 'SELECT * INTO BACKUPTABLE_' + #DATE + #TIME
+ '
FROM TABLE
WHERE ID IN (' + '''' + #ID + ''')'
--EXEC #query
PRINT #QUERY
I have tried to do a replace above but i want it so that an end user can PASTE into the values and my script will take care of the commas and properly form it. It should also strip out the last commas from the end.
My output needs to read:
SELECT * INTO BACKUPTABLE_201606061503
FROM TABLE
WHERE ID IN ('W0128001','32322','32323','3232323','2323232')
For one thing, you don't surround it with single quotes:
SET #QUERY = 'SELECT * INTO BACKUPTABLE_' + #DATE + #TIME + '
FROM TABLE
WHERE ID IN (' + #ID + ')';
There are other ways to pass comma-delimited values to a SQL statement, including using a split() function or XML.
CREATE PROCEDURE [dbo].[CreateBackupTable]
#ID varchar(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #DATE VARCHAR(50)= CONVERT(VARCHAR(8), Getdate(), 112);
DECLARE #TIME VARCHAR(50) = Replace(CONVERT(VARCHAR(5), Getdate(), 108), ':', '')
declare #xml xml,#SQL NVARCHAR(MAX);
set #xml = N'<root><r>' + replace(#ID,',','</r><r>') + '</r></root>'
SET #SQL = N' SELECT * INTO ' + QUOTENAME('BACKUPTABLE_' + #DATE + #TIME)
+ N' from TableName '
+ N' where ID IN (
select r.value(''.'',''varchar(max)'') as item
from #xml.nodes(''//root/r'') as records(r)
)'
exec sp_executesql #sql
, N'#ID varchar(100), #xml XML'
, #ID
, #Xml
END

How to use DATETime Column in dynamic query in sql server?

I have a Stored Proc which is using for Search Applicants is written as below:
/*
AUTHOR :
CREATION DATE :
NOTES :
PURPOSE :
MODIFIED BY :
MODIFICATION DATE :
*/
ALTER PROCEDURE USP_GET_ApplicantByFilter
(
#ApplicantName VARCHAR(100)='Ram',
#AgeFrom INT=0,
#AgeTo INT=0,
#Experience INT=0,
#ExperienceMonths INT=0,
#City VARCHAR(100)='',
#QualificationID INT=0,
#PositionID INT=0,
#ApplyDateFrom DATETIME='2010-06-29 00:00:00.000',
#ApplyDateTo DATETIME=NULL,
#SortColumn Varchar(128)='ApplicantID',
#SortDirection Varchar(56)='desc',
#Page int=1,
#RecsPerPage int =10
)
AS
DECLARE #SQL VARCHAR(MAX)
DECLARE #DSQL VARCHAR(MAX)
DECLARE #whereCondition VARCHAR(1024)
DECLARE #FirstRec int, #LastRec int
SET #FirstRec = (#Page - 1) * #RecsPerPage
SET #LastRec = (#Page * #RecsPerPage + 1)
Declare #SectionCount int;
Set NoCount On
Begin
SET #SQL='Select ROW_NUMBER() over( order by '+#SortColumn + ' ' +#SortDirection +') rownum, tblApplicants.ApplicantID, tblApplicants.ApplicantName, tblApplicants.FatherName, tblApplicants.DateOfBirth, tblApplicants.QualificationID, tblApplicants.EMailID, tblApplicants.Address, tblApplicants.City, tblApplicants.State, tblApplicants.Phone,
tblApplicants.ApplyDate, tblApplicants.PositionID, tblApplicants.isActive, tblPositionMaster.PositionName
FROM tblApplicants INNER JOIN tblPositionMaster ON tblApplicants.PositionID = tblPositionMaster.PositionID
WHERE 1=1 AND tblApplicants.isActive=1 '
if #ApplicantName!=''
begin
SET #sql +=' AND tblApplicants.ApplicantName like ''%'+ #ApplicantName +'%'''
end
if #AgeFrom!=0
begin
SET #SQL+=' AND DATEDIFF(YEAR,tblApplicants.DateOfBirth, GETDATE()) >= '+#AgeFrom
end
if #AgeTo!=0
begin
SET #SQL+=' AND DATEDIFF(YEAR,tblApplicants.DateOfBirth, GETDATE()) <= '+#AgeTo
end
if #ApplyDateFrom IS NOT NULL
begin
SET #SQL+= ' AND CONVERT(DATETIME,tblApplicants.ApplyDate,101) ='+ CONVERT(DATETIME,#ApplyDateFrom,101)
end
SET #DSQL ='SELECT * from (' + #SQL +') AS tbl'
print #DSQL
DECLARE #TEMPResult TABLE(RowNum INT,
ApplicantID int,
ApplicantName varchar(100),
FatherName varchar(200),
DateOfBirth DATETIME,
QualificationID int,
EMailID varchar(200),
Address varchar(200),
City varchar(200),
State varchar(200),
Phone varchar(200),
ApplyDate DATETIME,
PositionID int,
isActive int,
PositionName varchar(200)
)
INSERT INTO #TEMPResult EXEC(#DSQL)
SELECT (Select Count(*) from #TEMPResult) as Count, * FROM #TEMPResult WHERE RowNum > #FirstRec AND RowNum < #LastRec
RETURN
END
i want to apply "=>" and "<=" operators on ApplyDate. every time i got "*Conversion failed when converting date and/or time from character string.
*"
please help me how can apply these operators on ApplDate
SET #SQL+= ' AND CONVERT(DATETIME,tblApplicants.ApplyDate,101) ='+ CONVERT(DATETIME, #ApplyDateFrom, 101)
change it to:
SET #SQL+= ' AND CONVERT(DATETIME, tblApplicants.ApplyDate, 101) = CONVERT(DATETIME, ''' + cast(#ApplyDateFrom as nvarchar) + ''', 101)'
Replace this line
AND CONVERT(DATETIME,tblApplicants.ApplyDate,101) ='+ CONVERT(DATETIME,#ApplyDateFrom,101)
Updated
AND DATEDIFF(DD,tblApplicants.ApplyDate, CAST(''' + CAST(#ApplyDateFrom as varchar) + ''' as datetime)) = 0
for more look this query
DECLARE #ApplyDateFrom DATETIME='2010-06-29 00:00:00.000'
DECLARE #QUERY varchar(max)
SET #QUERY =
'SELECT DATEDIFF(DD,GETDATE(), CAST(''' + CAST(#ApplyDateFrom as varchar) + ''' as datetime))'
PRINT #QUERY
#AgeFrom is an int. You need to convert it to a varchar before concatentating it to a string.
'AND DATEDIFF(YEAR,tblApplicants.DateOfBirth, GETDATE()) >= '+convert(varchar(5),#AgeFrom)
Not that this will work, of course, as datediff(year... won't give you an age. eg:
select DATEDIFF(YEAR,'2000-12-25','2013-10-01')
will return 13, not 12.
Similarly for ApplyDate convert that to a string
CONVERT(DATE,tblApplicants.ApplyDate,101) = ''' + CONVERT(varchar(20),#ApplyDateFrom,111) + ''''
To be honest though, this whole approach looks like a bad idea to me.
you just need to make sure the parameter before it come into your stored procedured is in this format yyyy-MM-dd HH:mm:ss
then you're save to compare using "<=" and ">=" and doesn't need to convert it to other format just compare like this
tblApplicants.ApplyDate >='2013-10-01 18:00:00'
You need to cast applydate to string before concatenate to dynamics sql.
Mean
SET #SQL+= ' AND CONVERT(DATETIME,tblApplicants.ApplyDate,101) ='+ cast (CONVERT(DATETIME,#ApplyDateFrom,101) AS VARCHAR)

sql dates as column name

I want a table with columns named after dates.
example:
SELECT * AS GETDATE() FROM mytable;
From what I've read on the internet, it looks as though I will need to use dynamic SQL (?) something in the lines of this:
DECLARE #dt smalldatetime
SET #dt = GETDATE()
DECLARE #str varchar(100)
SET #str = 'SELECT * AS ' + convert(varchar(100), GETDATE(), 120) + ' FROM mytable'
EXEC(#str);
But this doesn't work. says "incorrect syntax near the keyword 'AS'
All I had to do was change from SELECT * to SELECT [the thing i needed]
DECLARE #dt smalldatetime
SET #dt = GETDATE()
DECLARE #str varchar(100)
SET #str = 'SELECT Item AS ' + convert(varchar(100), GETDATE(), 120) + ' FROM mytable'
EXEC(#str);
this works.
Try this:
DECLARE #dt smalldatetime
SET #dt = GETDATE()
DECLARE #str varchar(100)
SET #str = 'SELECT Item AS '+'''' + convert(varchar(100), GETDATE(), 120) +'''' + ' FROM mytable'
EXEC(#str);

A String Manipulation Puzzle in SQL Server 2008 R2

This information I have:
Column workflowname has this value ='12STD_Orientations_Workflow'
Column canceldate has a date value
I need to assign a value to the column campaignname like this:
let's say the value in canceldate is in November 2012, the value has to be '12STD_Orientations_2012_Nov'. If the value is in January 2013, the value has to be '12STD_Orientations_2013_Jan'. And so on.
I was thinking about doing a function and assign the value of canceldate (in the INSERT clause) by calling MyFunction(workflowname,canceldate). but I don't know how to write the code inside the function!
Here is a version that will produce the result that you want. This version reverses the current value of the #str value and then looks for the first _ in the string:
declare #str varchar(100) = '12STD_Orientations_Workflow'
declare #dt datetime = '2012-01-01'
select left(#str, len(#str) - charindex('_', REVERSE(#str)))
+ '_'
+ cast(YEAR(#dt) as char(4))
+ '_'
+ CONVERT(char(3), #dt, 109)
See SQL Fiddle with Demo
Then if you want to place this in a function, you can use:
create function dbo.New_Workflow
(
#origName varchar(200),
#dt datetime
)
RETURNS varchar(200)
AS
BEGIN
declare #newvalue varchar(100)
select #newvalue = left(#origName, len(#origName) - charindex('_', REVERSE(#origName)))
+ '_'
+ cast(YEAR(#dt) as char(4))
+ '_'
+ CONVERT(char(3), #dt, 109)
RETURN #newvalue
END;
Then to call this you can use:
declare #str varchar(100) = '12STD_Orientations_Workflow'
declare #dt datetime = '2012-11-01'
select dbo.New_Workflow(#str, #dt)
See SQL Fiddle with Demo
The result is:
| COLUMN_0 |
-------------------------------
| 12STD_Orientations_2012_Nov |
Now if you need to pull this from a table, you would use:
select dbo.New_Workflow(yourWorkFlowNameCol, yourDateColumn)
from yourtable
CREATE FUNCTION dbo.MyFunction
(
#originalString VARCHAR(200),
#dateFromField DATETIME
)
RETURNS varchar(200)
AS
BEGIN
DECLARE #newString VARCHAR(200)
SELECT #newString = LEFT(#originalString,19) + LEFT(CONVERT(VARCHAR(19),#dateFromField,109),3)
RETURN #newString
END;