Passing SQL stored procedure entirety of WHERE clause

后端 未结 5 2020
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 19:01

I have a SQL stored procedure of the form

SELECT [fields] FROM [table] WHERE @whereSql

I want to pass the procedure an argument (@whereSql)

5条回答
  •  天涯浪人
    2020-12-11 19:39

    I believe this can be done using Dynamic SQL. See below:

    CREATE PROCEDURE [dbo].[myProc]
    @whereSql nvarchar(256)
    
    AS
        EXEC('SELECT [fields] FROM [table] WHERE ' + @whereSql)
    GO
    

    That said, you should do some serious research on dynamic SQL before you actually use it. Here are a few links that I came across after a quick search:

    • http://www.sommarskog.se/dynamic_sql.html

    • http://msdn.microsoft.com/en-us/library/aa224806%28SQL.80%29.aspx

    • http://www.itjungle.com/fhg/fhg100505-story02.html

提交回复
热议问题