Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

SQL Server Dynamic Queries

$
0
0

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:

Common: tblCommon Specific: tblSpecific

Is there way I can pass the name "tblSpecific" into a single stored procedure as a variable, like the following?

SELECT .... FROM tblCommon c INNER JOIN @TABLE s on c.primaryKey = s.foreignKey

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.


Viewing all articles
Browse latest Browse all 3160

Latest Images

Trending Articles



Latest Images