简体   繁体   中英

Getting Conversion failed when converting date and/or time from character string

I am creating a stored procedure dynamically where I have a main clause and a where clause:

CREATE ROCEDURE [dbo].[spLocal_GetData]        
    @CreatedOnDate DateTime      
AS
    declare @MainQuery varchar(max),      
            @WhereClause varchar(1000) 

    Select @MainQuery = 'Select column from Table T1'
    Select @WhereClause = ' Where  T1.CreateOn >='+@CreatedOnDate

Now while executing the stored procedure:

DECLARE @CreatedOnDate datetime
SET @CreatedOnDate =GETDATE()

EXECUTE @RC = [dbo].[spLocal_GetData] ,@CreatedOnDate
GO

I get the error:

Conversion failed when converting date and/or time from character string.

Edit1:

declare @MainQuery varchar(max),      
@WhereClause varchar(1000)      

Select @MainQuery =N'Select ..'
Select @WhereClause = N' Where  T1.CreatedOn>=@CreatedOnDate'


EXECUTE @RC = [dbo].[spLocal_GetNonConformance] 
   ,N'@CreatedOnDate DateTime'
GO

You are getting the error because you are trying to concatenate a datetime value with a string ' Where T1.CreateOn >='+@CreatedOnDate , Datetime being a higher precedence data type sql server tries to convert the string value to datetime and fails.

You method is prone to sql-injection you should use dynamic sql for this. Although for this simple query you do not even need dynamic sql but assuming the actual query is a bit more complex and you actually need dynamic sql for it you would do it something like this.....

Try this, it will also protect you against sql-injection attack......

CREATE ROCEDURE [dbo].[spLocal_GetData]        
    @CreatedOnDate DateTime      
As   
BEGIN
        declare @MainQuery nvarchar(max)

SET @MainQuery = N'Select column from Table T1'
               + N' Where  T1.CreateOn >=  @CreatedOnDate'

Exec sp_executesql @MainQuery
                  ,N'@CreatedOnDate DateTime'
                  ,@CreatedOnDate 

END

You have to convert DateTime to varchar before appending it to dynamic sql

so

Select @WhereClause =' Where  T1.CreateOn >='+convert(varchar(20),@CreatedOnDate,120) 

will work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM