SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Date problem in dynamic SQL
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Corobori
Yak Posting Veteran

Chile
99 Posts

Posted - 06/12/2012 :  21:21:42  Show Profile  Visit Corobori's Homepage  Reply with Quote
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)

Singapore
16745 Posts

Posted - 06/12/2012 :  23:37:54  Show Profile  Reply with Quote
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
Time is always against us

Go to Top of Page

Corobori
Yak Posting Veteran

Chile
99 Posts

Posted - 06/13/2012 :  22:47:35  Show Profile  Visit Corobori's Homepage  Reply with Quote
Thanks khtan, it's working.
I'll read your page too.

jean-luc
www.corobori.com
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.08 seconds. Powered By: Snitz Forums 2000