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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Date problem in dynamic SQL

Author  Topic 

Corobori
Posting Yak Master

105 Posts

Posted - 2012-06-12 : 21:21:42
The stored procedure shown below isn't working as expected when I am passing down a date as a parameter


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[sp_tblEvents_Search_sel]
@Ev_C_Id int =0,
@Ev_Tipo int =0,
@Evd_Date datetime = '1/1/1900'
As
Begin

SET NOCOUNT ON;

declare @swhere varchar(4000)

declare @sSQL varchar(5000)

set @swhere = COALESCE(@swhere + ' ','')

set @sSQL = COALESCE(@sSQL + ' ','')

if ( @Evd_Date <>'1/1/1900')
begin
set @swhere = @swhere + ' AND DATEDIFF(d, GETDATE(), ' + cast(@Evd_Date as datetime) + ') =0 '
end
if (@Ev_C_Id<>0)
begin
set @swhere = @swhere + ' AND Ev_C_Id=' + CONVERT(nvarchar(11), @Ev_C_Id)
end
if (@Ev_Tipo<>0)
begin
set @swhere = @swhere + ' AND Ev_Tipo=' + CONVERT(nvarchar(11), @Ev_Tipo)
end


set @sSQL = 'SELECT Ev_C_Id, Ev_Tipo,S_Name, Sd_Title, S_Foto, Sd_LanguageId, C_Name, Ev_Name, Ev_Hour, Ev_Location, Ev_Fee, Ev_Description, iDays, Sd_Id, Evd_Date, S_Logo, Ev_DisplayUntil, Evd_Id, Ev_URL,S_Id, sType,S_Premium, S_PremiumDate FROM vwEventsDates WHERE Ev_Estado=1 ' + @swhere + ' ORDER BY Evd_Date '

exec(@sSQL)

End


The issue is here


set @swhere = @swhere + ' AND DATEDIFF(d, GETDATE(), ' + cast(@Evd_Date as datetime) + ') =0 '


When running the sp it says "Conversion failed when converting date and/or time from character string."

Any clue ?

jean-luc
www.corobori.com

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2012-06-12 : 23:37:54
1. you need to convert the @Evd_Date to string before concatenate

set @swhere = @swhere + ' AND DATEDIFF(d, GETDATE(), ''' + convert(varchar(10), @Evd_Date, 121) + ''') =0 '

2. you should use sp_executesql instead of exec() as sp_executesql allows you to pass in variable as a parameter

You should also take a look at http://www.sommarskog.se/dynamic_sql.html


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

Corobori
Posting Yak Master

105 Posts

Posted - 2012-06-13 : 22:47:35
Thanks khtan, it's working.
I'll read your page too.

jean-luc
www.corobori.com
Go to Top of Page
   

- Advertisement -