Mssql Stored Procedure table name and field name as variables

Source: Internet
Author: User
The implementation method of mssql Stored Procedure table name and field name is variable. For more information, see.

The implementation method of mssql Stored Procedure table name and field name is variable. For more information, see.

Direct error reporting without using dynamic statements

Incorrect
The Code is 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, status 1, process testpapers, 1st rows
There is a syntax error near the keyword 'select.
Message 1087, Level 15, status 2, process testpapers, 1st rows
The table variable "@ tems" must be declared ".

First, you must use dynamic statements to set the table name or field as a variable.

Incorrect
The Code is 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, status 2, 1st rows
The table variable "@ tems" must be declared ".

Write the table name and field name to exec.

Correct
The Code is 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

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.