SQL statement-exec execution

Source: Internet
Author: User

Dynamic SQL statement Basic syntax
1: Normal SQL statements can be executed with exec

Eg:select * Fromtablename
Exec (' select * from TableName ')
Exec sp_executesql n ' select * fromtablename '--please note that the string must be added n before

2: Field name, table name, database name, etc. as variables, you must use dynamic SQL

eg
DECLARE @fname varchar (20)
Set @fname = ' Filedname '
Select @fname Fromtablename-Error, does not prompt for errors, but results are fixed values filedname, not required.
Exec (' select ' + @fname + ' fromtablename ')--note the plus space on the edge of the single quotation mark before and after

Of course, changing the string to a variable can also
DECLARE @fname varchar (20)
Set @fname = ' Filedname '--set field name

DECLARE @s varchar (1000)
Set @s = ' SELECT ' + @fname + ' from TableName '
Exec (@s)--Success
EXEC sp_executesql @s--This sentence will be an error

DECLARE @s Nvarchar (1000)--note here to Nvarchar (1000)
Set @s = ' SELECT ' + @fname + ' from TableName '
Exec (@s)--Success
EXEC sp_executesql @s--this sentence is correct

3. Output parameters
DECLARE @num int,
@sqls nvarchar (4000)
Set @sqls = ' SELECT count (*) from TableName '
EXEC (@sqls)
--How do I put the exec execution result into a variable?

DECLARE @num int,
@sqls nvarchar (4000)
Set @sqls = ' Select @a=count (*) from TableName '
EXEC sp_executesql @sqls, N ' @a int output ', @num output
Select @num

SQL statement-exec execution

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.