Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Logic within Stored Proedures?????? 1

Status
Not open for further replies.

pwel

Programmer
Aug 18, 1999
79
GB
Can I dynamically build a WHERE clause within a store procedure, depending the values of certain variables passed into it?

The ideal scenario would be a series of if...else statements to determine the condition of the WHERE clause.
 
Hiya,

Yes, you can, but only if you use dynamic SQL. eg.

DECLARE @sql VARCHAR(255)

IF something = something_else
SELECT @sql = 'WHERE x = y'
ELSE
SELECT @sql = 'WHERE y = z'

EXEC ('UPDATE table ' +
'SET field = field ' +
'field = field ' +
@sql)

HTH

Tim
 
You could use a CASE statement, which has the advantage of being processed more efficiently. Malcolm Wynden
Authorized Crystal Engineer
malcolm@wynden.net
 
Thanks Tim,

That is exactly what I wanted to do.........

Paul W.
 
I am having problems using an (int) value in the WHERE string, as the WHERE string is defined as a varchar, I keep getting an error when SQL Server tries to convert it to an int.

Is there command to parse that part of the string as an int??
 
Hiya,

Yes, you need to use the convert function:

eg:

@sql = @sql + CONVERT(INT, variable)

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top