• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 225
  • Last Modified:

sql date format

I have a copy of some code i need to adjust. the following code sets the date as 160611
i need to change the date to the following format 20110417.

please ignore the actual dates as they are just examples.
also with my print statement nothing happens.
set dateformat dmy 

--***********************************
--Declare Variables
--***********************************
declare 
	 @Date varchar(10)
	 , @FileDate varchar(8)


SET @FileDate = CONVERT(VARCHAR,
					CASE WHEN DATEPART(DD,@Date) < 10 
						 THEN '0' + CONVERT(VARCHAR,DATEPART(DD,@Date))
						 ELSE CONVERT(VARCHAR,DATEPART(DD,@Date))
					END
				 )
				+ CONVERT(VARCHAR,
					CASE WHEN DATEPART(MM,@Date) < 10 
						 THEN '0' + CONVERT(VARCHAR,DATEPART(MM,@Date))
						 ELSE CONVERT(VARCHAR,DATEPART(MM,@Date))
					END
				 )
				+ CONVERT(VARCHAR,RIGHT(DATEPART(YYYY,@Date),2))


print @FileDate

Open in new window

0
aneilg
Asked:
aneilg
1 Solution
 
DerZaubererCommented:
--***********************************
--Declare Variables
--***********************************
declare 
	 @Date varchar(10)
	 , @FileDate varchar(8)


SET @FileDate = CONVERT(VARCHAR,DATEPART(YYYY,@Date))
				+ CONVERT(VARCHAR,
					CASE WHEN DATEPART(MM,@Date) < 10 
						 THEN '0' + CONVERT(VARCHAR,DATEPART(MM,@Date))
						 ELSE CONVERT(VARCHAR,DATEPART(MM,@Date))
					END
				 )
				+ CONVERT(VARCHAR,
					CASE WHEN DATEPART(DD,@Date) < 10 
						 THEN '0' + CONVERT(VARCHAR,DATEPART(DD,@Date))
						 ELSE CONVERT(VARCHAR,DATEPART(DD,@Date))
					END
				 )


print @FileDate

Open in new window

0
 
Lee SavidgeCommented:
If @date was a datetime data type you can just do this:

SET @FileDate = select CONVERT(nvarchar(10), @Date, 112)
0
 
LowfatspreadCommented:
set @filedate=convert(char(8),@date,112)
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
aneilgAuthor Commented:
thanks guy.
one last question why does my print @FileDate not work.
0
 
Lee SavidgeCommented:
It does work. It prints to the messages tab. Use:

Select @FileDate

This returns it as a recordset.
0
 
aneilgAuthor Commented:
silly me. thanks.
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
btw, here my article to handle date/time correctly:
http://www.experts-exchange.com/A_1499.html
0
 
aneilgAuthor Commented:
thanks
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now