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)
 Dynamic SQL

Author  Topic 

evanburen
Posting Yak Master

167 Posts

Posted - 2009-10-29 : 12:17:02
I can't figure out why I'm getting this error message

Msg 137, Level 15, State 2, Procedure p_SearchED, Line 23
Must declare the scalar variable "@xid_field".


CREATE PROCEDURE [dbo].[p_SearchED]

@id_field int = NULL

AS
DECLARE @sql nvarchar(max),
@paramlist nvarchar(4000)

SELECT @sql =
'SELECT * FROM Requests
WHERE 1 = 1'

IF @id_field IS NOT NULL
SELECT @sql = @sql + ' AND id_field = @xid_field'

--PRINT @sql

SELECT @paramlist =
'@xid_field int'

EXEC sp_executesql @sql, @paramlist, @xid_field

evanburen
Posting Yak Master

167 Posts

Posted - 2009-10-29 : 13:01:50
The error was on this line

EXEC sp_executesql @sql, @paramlist, @xid_field

It should have been this

EXEC sp_executesql @sql, @paramlist, @id_field

Thanks anyway
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-10-30 : 02:40:47
You can avoid dynamic sql by using


CREATE PROCEDURE [dbo].[p_SearchED]

@id_field int = NULL

AS
DECLARE @sql nvarchar(max),
@paramlist nvarchar(4000)

SELECT * FROM Requests
WHERE id_field = @id_field or @id_field IS NULL


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

jezemine
Master Smack Fu Yak Hacker

2886 Posts

Posted - 2009-10-30 : 02:49:52
the bible of dynamic search conditions:

http://sommarskog.se/dyn-search-2005.html


elsasoft.org
Go to Top of Page
   

- Advertisement -