简体   繁体   中英

SQL Stored Procedure Unknown Where Clause

Is there a way to write an SQL stored proc, where it isn't known until run time how many parameters are to be included in the where clause and which columns those target?

Thanks.

You could build dynamic sql in the stored proc and then execute it. I wouldn't recommend doing this, but it is an option.

If you do go this route, make sure you give this article a thorough read.

UPDATE:

Disclaimer - the article above is specific to SQL Server. Some of it may still apply though (I don't know enough about Oracle to say one way or the other).

I would recommend taking a look at this article for Oracle specific information on Dynamic SQL.

If you have many columns that you can search by, then building a dynamic sql statement would be easier but... you have to worry about sql injection

OR

if you know the columns that will be searched, create an optional parameter for each of those columns and assign a default value of null to them

Edit: added sample in sql server but easily portable to oracle

CREATE PROCEDURE dbo.test
(
    @col1   varchar(50) = null,
    @col2   int = null,
    @col3   datetime = null
)
AS

    SELECT  col1, col2, col3
    FROM    someTable
    WHERE   (@col1 IS NULL OR col1 = @col1)
    AND     (@col2 IS NULL OR col2 = @col2)
    AND     (@col3 IS NULL OR col3 = @col3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM