Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Can I Do Dynamic Query Construction in SQL Server SP
Message
From
11/10/2009 16:24:55
Cetin Basoz
Engineerica Inc.
Izmir, Turkey
 
 
To
11/10/2009 14:15:46
Bill Drew
Independent Consultant
Chicago, Illinois, United States
General information
Forum:
Visual FoxPro
Category:
Client/server
Miscellaneous
Thread ID:
01428769
Message ID:
01428843
Views:
50
>>>I have a VFP query screen that has several text boxes for entry of a the necessary values for a look up by last, first, dob, year of claim, and two case id numbers. In the "Do Query" click code, I create an SQL Select statement which combines the variables based on a useful logic (ie last and first and dob can claim year can be combined using AND logic -- if either of the claim IDs are filled in then the logic is a simple search just on the ID. if "is contained in" is checked the target word is preceded with the %. With SQLEXED, It is a great tool. But the company policy is to use stored procedures.
>>>
>>>So now I'm trying to implement it as a stored procedure. But I don't have enough experience to write this conditional logic in the stored procedure. If I pass all the query variables to the SP, can I evaluate which ones are non null and conditionally execute one Select statement or another?? If so, how does this procedural code look?
>>
>>You can use
>>
>>Isnull( @theParameter, replacementValueIfParameterIsNull)
>>
>>or:
>>
>>case when @theParameter is NULL then ... else @theParameter end
>>
>>T-SQL also supports conditionals like If ... then ... else
>>
>>Cetin
>
>Can you develop it a little more for me?
>
>For example
>
>Would I be about to conditionally call one SQL Select based on checking for Null parameters and call another SQL Select based on a different combination of Null and Non Null parameters??

That depends on your strategy. You could replace the values with values that mean "ALL" when it is NULL or entirely drop the condition when it is NULL. ie:
create procedure MySP ( @customerId varchar(10) = NULL, @employeeID int = NULL )
as
begin
   select * from Orders
   where 
          CustomerID = case when @customerId is null then CustomerID else @CustomerID end
   and EmployeeID = case when @employeeID is null then employeeID else @employeeID end  
end
You could then do:
Exec MySP
Exec MySP 'BONAP'
Exec MySP 'BONAP',4
Exec MySP null,4
The other approach is based on sp_executeSQL and builds the query as a string dropping the NULL conditions.
Cetin
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform