SQL Server Cast
-
Posted on June 4, 2010 by Derek Dieter
-
0
The SQL Server cast function is the easiest data type conversion function to be used compared to the CONVERT function. It takes only one parameter followed by the AS clause to convert a specified value.
A quick example is the following:
[cc lang=”sql”]
SELECT
UserID_String = CAST(UserID AS varchar(50))
FROM dbo.User
[/cc]
This example will convert the integer to a character value. So what is the use of this? Well, more likely that not if you’re on this page you know the use, however it is usually used to concatenate or perform string like comparisons on numeric values, or to convert a numeric or string value in order to compare.
An example is when trying to manually construct date parts into a custom format, you need to append the number comprising the date into a string. Say you wanted to make the date 2010/06/05 into a custom format of: 20100605. In order to do so, you need to utilize the datepart function then concatenate the results. The problem is, when you try to concatenate the results of datepart, instead of concatenating, the number get summed together. To get around this, simply use CAST.
[cc lang=”sql”]
DECLARE @mydate as DATETIME
SET @mydate = GETDATE()
— wrong way
SELECT DATEPART(yy, @mydate) + DATEPART(mm, @mydate) + DATEPART(dd, @mydate)
— output: 2020
— correct way
SELECT
CAST(DATEPART(yy, @mydate) AS VARCHAR(10))
— append a zero before the date so we get two digits on a one digit month
+ RIGHT(‘0’ + CAST(DATEPART(mm, @mydate) AS VARCHAR(10)), 2)
— append a zero before the date so we get two digits on a one digit day
+ RIGHT(‘0’ + CAST(DATEPART(dd, @mydate) AS VARCHAR(10)), 2)
— output: 20100604
[/cc]
- Comments (RSS)
- Trackback
- Permalink
took me a while to check what’s going on:
I think you wanted RIGHT instead of LEFT
*ggg*
script doesnot work for all months…all days…in a month..it gives wrong output..
select cast (datepart(YEAR, getdate()) as varchar)
+ LEFT(‘0’+cast(datepart(MM, getdate())as varchar),2)
+ left(‘0’+cast(datepart(DAY, getdate()) as varchar),2)
———— ————————————————————
output.
20140303 but date is 31st March 2014
Is the word to be used really ‘append’? “you need to append the number comprising the date into a string.” Is it really a ‘padding’ of the number 0?
What about @mydate =’2009-12-11′, output =20090201 ?
Hi, You can find that answer here:
http://sqlserverplanet.com/sql/cast-date-with-no-time/
SELECT CONVERT(varchar(12),GETDATE(), 112) — 20090629