- /************************************************************************************************************** ****************************************
- Dynamic statement syntax: Exec/sp_executesql syntax
- Finishing Man: China Wind (Roy)
- Date: 2008.06.06
- *************************************************************************************************************** ***************************************/
- Dynamic statement Syntax:
- --Method 1 query table changed to dynamic
- SELECT * from sysobjects
- EXEC (' select id,name from sysobjects ')
- EXEC sp_executesql n' select id,name from sysobjects '-one more n for Unicode
- --Method 2: Field name, table name, database name, etc. as variables, use dynamic SQL
- DECLARE @FName varchar (20)
- Set @FName =' ID '
- EXEC (' select ' [email protected]+' from sysobjects where ' [email protected]+' =5 ')
- DECLARE @s varchar (1000)
- Set @s=n' SELECT ' [email protected]+' from sysobjects where ' [email protected]+' =5 '
- EXEC sp_executesql @s--will error
- declare @s nvarchar (1000)--Change to nvarchar
- Set @s=n' SELECT ' [email protected]+' from sysobjects where ' [email protected]+' =5 '
- EXEC sp_executesql @s--Success
- --Method 3: Input parameters
- DECLARE @i int,@s nvarchar (+)
- Set @i=5
- EXEC (' select Id,name from sysobjects where id= ' [email protected])
- Set @s=' select Id,name from sysobjects where [email protected] '
- EXEC sp_executesql @s,n' @i int ', @i--here input parameter to add N
- --Method 4: Output parameters
- DECLARE @i int,@s nvarchar (+)
- Set @s=' select @i=count (1) from sysobjects '
- --with Exec
- EXEC (' Declare @i int ' [Email protected]+' Select @i ')--add the entire statement with a string to execute.
- --With sp_executesql
- EXEC sp_executesql @s,n' @i int output ', @i output--here output parameter to add N
- Select @i
- --Method 5: Input and output
- --With sp_executesql
- DECLARE @i int, @con int,@s nvarchar (+)
- 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
- --with Exec
- DECLARE @i int,@s nvarchar (+)
- Set @i=5
- Select @s=' declare @con int select @con =count (1) from sysobjects where id> ' +rtrim (@i) +' select @con '
- EXEC (@s)
http://blog.csdn.net/roy_88/article/details/3020586
Dynamic statement SQL statement notation