Sunday, March 25, 2012

Cursor in stored procedure

I'm trying to do something like that:
CREATE PROCEDURE [dbo].[Test_Proc] (@.SearchText1 nvarchar(10), @.SearchText2
nvarchar(100), @.SearchText3 nvarchar(100)) AS
DECLARE @.SQLString NVARCHAR(4000)
DECLARE @.SQLSelect NVARCHAR(3000)
DECLARE @.SQLWhere NVARCHAR(1000)
SET @.SQLSelect = 'SELECT dbo.View_Clients.Client_id,
dbo.Contacts.Contact_id from dbo.View_Clients LEFT OUTER JOIN dbo.Contacts
ON dbo.View_Clients.Contact_ID = dbo.Contacts.Contact_id'
if @.SearchText1 = 'Client'
SET @.SQLWhere = ' WHERE dbo.View_Clients.Name_Fr = ?'
--Here I would use SearchText2 as parameter 1
if @.SearchText1 = 'Contact'
SET @.SQLWhere = ' WHERE dbo.Contacts.FName = ? and dbo.Contacts.LName
= ?'
--Here I would use SearchText2 as parameter 1 and SearchText3 as
parameter 2
Set @.SQLString = @.SQLSelect + @.SQLWhere
...
I want to Declare a cursor with this SQL String and supply the good
parameters. Is that possible?
If so, how? i'm a little lost when it comes to cursorsI think you are tying yourself in unnecessary knots, you appear to be
able to do this with just some static SQL:
SELECT dbo.View_Clients.Client_id,
dbo.Contacts.Contact_id from dbo.View_Clients LEFT OUTER JOIN
dbo.Contacts
ON dbo.View_Clients.Contact_ID = dbo.Contacts.Contact_id
WHERE (@.SearchText1 = 'Client' AND dbo.View_Clients.Name_Fr =
@.SearchText2)
OR (@.SearchText1 = 'Contact' AND dbo.Contacts.FName = @.SearchText2 AND
dbo.Contacts.LName = @.SearchText2)
Cheers
Will
P.S stay lost when it comes to cursors - it's safer

No comments:

Post a Comment