views:

136

answers:

3

Could anyone help me understand why the following query works fine in SQL 2000 and not in SQL 2005

In SQL 2005 it errors out "The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value"

DECLARE @Table table(date varchar(6),code char(1))
INSERT INTO @Table select '010209','N'
INSERT INTO @Table select '032809','N'
INSERT INTO @Table select space(6),'N'

select * FROM  @Table  
WHERE  
(
      (
            date <> ''  
            AND        
            GETDATE() < CAST(LEFT(date, 2) + '/' +  SUBSTRING(date, 3, 2) + '/' +  RIGHT(date,2) AS SMALLDATETIME)
      )  
      OR code = 'Y')
+2  A: 

The error is exactly what it says.

No matter how hard you try, ' / / ' will never ever be any date.

leppie
A: 

Use

date.RTRIM() <> ''

instead of

date <> ''
Joakim Backman
+2  A: 

Yes, leppie could have been a bit clearer, but <> '' does not match your space(6).

This will work (using ltrim/rtrim)

DECLARE @Table table(date varchar(6),code char(1))
INSERT INTO @Table select '010209','N'
INSERT INTO @Table select '032809','N'
INSERT INTO @Table select space(6),'N'

select * FROM  @Table  
WHERE  
(
      (
            ltrim(rtrim(date)) <> ''  
            AND        
            GETDATE() < CAST(LEFT(date, 2) + '/' +  SUBSTRING(date, 3, 2) + '/' +  RIGHT(date,2) AS SMALLDATETIME)
      )  
      OR code = 'Y')
Wayne
It worked but how come it does not throw any error in SQL 2000
rsapru
Let me try this one on the Original Query and then will mark you r Question as Answer . Thanks a lot. silly mistake on my part.
rsapru