SQL Server dynamic queries

前端 未结 6 708
盖世英雄少女心
盖世英雄少女心 2021-01-07 04:21

I have 15 stored procedures that return data from a common table and then join that table with a specific table to retrieve inventory.

Example:

Commo         


        
6条回答
  •  暖寄归人
    2021-01-07 05:03

    The way you do this is with dynamically generated SQL which is run through the sp_executesql() stored procedure.

    In general you pass in your required table name to your master procedure, build an ncharvar string of the SQL you want to execute, and pass that to sp_executesql.

    The curse and blessing of Dynamic SQL is about the best page I have seen for describing all the in's and out's.

    One of the biggest gotchas is that if you use dynamic SQL then the user who calls your stored procedure not only has to have execute permission on that procedure, but also has to have permission to access the underlying tables. The link I gave also describes how to get around that issue.

提交回复
热议问题