Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Datetime error

Author  Topic 

joelseverich
Starting Member

34 Posts

Posted - 2012-10-26 : 11:06:45
Hi,
I'm trying to run this code:

SET @Comm=' DECLARE curSum CURSOR FOR SELECT ISNULL(SUM(' + @Field + '),0) Total FROM Table WHERE Date>=' + @Date1 + ' AND Date<=' + @Date2

but I got this error:

cannot convert char to smalldatetime

please help me.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-10-26 : 11:30:21
Change it like shown below. HOWEVER, the string you are constructing looks like you are trying to build a query string for use in dynamic SQL. Two bad things about that:
a) dynamic sql is vulnerable to SQL injection, so avoid it if you can.
b) the sql string looks like you are using a cursor. Almost always, a cursor is a bad thing to use - it can slow down performance SUBSTANTIALLY.

If you post your requirements, people on the forum may be able to suggest better ways of writing the query. Take a look at this page for help in posting table DDL and data:http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

SET @Comm=' DECLARE curSum CURSOR FOR SELECT ISNULL(SUM(' 
+ @Field
+ '),0) Total FROM Table WHERE Date>='
+ CONVERT(varchar(32),@Date1 , 126) + ' AND Date<='
+ CONVERT(varchar(32),@Date2 , 126)
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-10-26 : 15:04:05
the reason is @date1 is not having dates in proper unambiguos format that it can interpret correctly.

see

http://visakhm.blogspot.com/2011/12/why-iso-format-is-recommended-while.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -