T-SQL (5) Dynamic T-SQL statement syntax

Source: Internet
Author: User
-- Method 1 change the query table to dynamic
Select * From Sysobjects
Exec ( ' Select ID, name from sysobjects ' )
Exec Sp_executesql n ' Select ID, name from sysobjects ' -- N is Unicode.

-- Method 2: use dynamic SQL
Declare @ Fname Varchar ( 20 )
Set @ Fname = ' ID '
Exec ( ' Select ' + @ Fname + ' From sysobjects where ' + @ Fname + ' = 5 ' )

Declare @ S Varchar ( 1000 )
Set @ S = N ' Select ' + @ Fname + ' From sysobjects where ' + @ Fname + ' = 5 '
Exec Sp_executesql @ S -- An error is reported.

Declare @ S Nvarchar ( 1000 ) -- Change to nvarchar
Set @ S = N ' Select ' + @ Fname + ' From sysobjects where ' + @ Fname + ' = 5 '
Exec Sp_executesql @ S -- Successful

-- Method 3: Enter Parameters

Declare @ I Int , @ S Nvarchar ( 1000 )
Set @ I = 5
Exec ( ' Select ID, name from sysobjects where id = ' + @ I )

Set @ S = ' Select ID, name from sysobjects where id = @ I '
Exec Sp_executesql @ S , N ' @ I int ' , @ I -- N is required for the input parameter.

-- Method 4: Output Parameters

Declare @ I Int , @ S Nvarchar ( 1000 )
Set @ S = ' Select @ I = count (1) From sysobjects '

-- Use Exec
Exec ( ' Declare @ I int ' + @ S + ' Select @ I ' ) -- Add the entire statement to the string for execution.

-- Use sp_executesql
Exec Sp_executesql @ S , N ' @ I int output ' , @ I Output -- N is added to the output parameter.
Select @ I

-- Method 5: Input and Output

-- Use sp_executesql
Declare @ I Int , @ Con Int , @ S Nvarchar ( 1000 )
Set @ I = 5
Select @ S = ' Select @ con = count (1) From sysobjects where ID> @ I '
Exec Sp_executesql @ S , N ' @ Con int output, @ I int ' , @ Con Output, @ I
Select @ Con

-- Use Exec
Declare @ I Int , @ S Nvarchar ( 1000 )
Set @ I = 5
Select @ S = ' Declare @ con int select @ con = count (1) From sysobjects where ID> ' + Rtrim ( @ I ) + ' Select @ con '
Exec ( @ S )

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.