MSSQL stored Procedure table name and field name as variables implementation method _mssql

Source: Internet
Author: User
Tags mssql
No direct error using dynamic statements

of the wrong
Copy Code code as follows:

ALTER PROC Testpapers
As
Begin
declare @tems nvarchar (max), @zidaun nvarchar (max)
Set @tems =select * from @tems ORDER by @zidaun
EXEC (@tems)
End
EXEC testpapers

Message 156, Level 15, State 1, Process testpapers, line 1th
There are syntax errors near the keyword ' select '.
Message 1087, Level 15, State 2, Process testpapers, line 1th
The table variable "@tems" must be declared.

To get a table name or field to be a variable, use the dynamic statement first

of the wrong
Copy Code code as follows:

ALTER PROC Testpapers
As
Begin
declare @tems nvarchar (max), @zidaun nvarchar (max)
Set @tems = ' SELECT * from @tems order by @zidaun ';
EXEC (@tems)
End

EXEC testpapers

Message 1087, Level 15, State 2, line 1th
The table variable "@tems" must be declared.

Write the table name and field name to exec inside

Right to
Copy Code code as follows:

ALTER PROC Testpapers
As
Begin
declare @startRow nvarchar (max), @tems nvarchar (max), @zidaun nvarchar (max)
Set @startRow = ' temp '
Set @tems = ' select * from ';
Set @zidaun = ' p_id ';
EXEC (@tems + @startRow + ' ORDER BY ' + @zidaun)
End

EXEC testpapers
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.