Senaste inläggen 

Taggar 

DECIMAL     central management server     XP_cmdshell     DTA     profile     T-SQL     concatenation     login error     sql browser     bugs     Datawarehouse     BOL     package load     improve     SSAS     performance     SQL Server 2012     filter     Business Intelligence     Page life expectancy     SSRS 2008     transactions     error     Microsoft     SQL Server     connection     access denied     function     AcquireConnection     connect     page splits     sql 2008     Logins     virtuell     0xC0202009     undocumented procedures     history     2008     security     create index     HADR     temp table     Reports     CTE     HEAP     features     CMS     2011     Techdays     sql 2005     2000     reorganize index     #am_get_querystats     Extended Event     CTP1     constraint     CU1     feedback     SSRS     SQL server codename Denali     0xC0010014     data warehouse     gratis verktyg     sp_MSForEachDB     parallelism     rebuild     dbmail     Cluster     sp1     platsannons SQL utvecklare     parameters     clean up     SQL2008     CU3     Activity Monitor     Säkerhet     2005     resource governor     Trace Flag     SSIS     SQL Denali

SQL Server - cast string into date vs datetime

Skrivet den 31 juli 2012 i T-SQL, Level 300, Håkan Winther, sv, en

I found a tricky question on http://www.sqlservercentral.com/Questions about casting strings into date vs datetime, and I want to share this with you, in case you missed it. (by the way, excellent site if you want to measure your knowledge and learn something new, thanks SQL server central)

Try the following code:

SET DATEFORMAT YDM;
GO

CREATE VIEW vDate(dt1, dt2)
AS
SELECT CAST('2012-04-10' AS DATETIME),CAST('2012-04-10' AS DATE
)
GO

SET DATEFORMAT YDM;
GO
SELECT * FROM vDate WHERE dt1=dt2;

SET DATEFORMAT YMD;
GO
SELECT * FROM vDate WHERE dt1=dt2;

DROP VIEW vDate; 

It turns out that the two selects from the veiw doesn't return the same result! :) The string casted to datetime is depending on the regional setting but date is not. The date datatype is language neutral and will always be casted as yyyymmdd.

If you want to learn more about how date and datetime are handled by the sql server engine you can read more on Tibor Karaszi's blog http://www.karaszi.com/SQLServer/info_datetime.asp or contact any of our SQL server consultants.

Skriv en kommentar