execute sp_executesql use variables to get the return value


最近用到,在网上查了下资料
注意加粗部分,sp_executesql 的参数必须为UNICODE,即NCHAR,NVARCHAR,NTEXT型,否则报错

Basic grammar of dynamic sql statement
1: Exec executes    
   
Select * from tableName
Exec ('select * from tableName')
Exec sp_executesql N'select * from tableName '-please note that N must be added before the string

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 from tableName-error, no error will be prompted, but the result is The fixed value FiledName is not required.
Exec ( 'select' + @fname + 'from tableName') - Note single quotation marks before and after the edge spaces plus

of course the string variables may also change
DECLARE @fname VARCHAR (20 is)
SET @fname = 'FiledName' --Set field name

declare @s varchar (1000)
set @s = 'select' + @fname + 'from tableName'





Nvarchar (1000)-Note that here changed to nvarchar (1000)
set @s = 'select' + @fname + 'from tableName'
Exec (@s)-successful
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
to put the execution result of exec 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 @numIf    
it is its own There are parameters in the stored procedure, you can also use sp_executesql directly

CREATE PROCEDURE demo
@test varchar(100)
as
return 1
go
declare @name int
exec @name=demo 'test'
select @name

There can be no functions in the parameters of the stored procedure demo
. If you want to pass a newid (), you must use local variables.Note
that the return value of the stored procedure must be an integer
declare @id
declare @name int
exec @ name = demo @id
select @name

mssql help

Execute Transact-SQL statements or batches that can be reused multiple times or dynamically generated. Transact-SQL statements or batches can contain embedded parameters.

grammar

sp_executesql [@stmt =] stmt
[
   
{, [@params =] N@#@parameter_name data_type [,...n]@# }
     {, [@param1 =] @#value1@# [,...n] }
]

parameter

[ @stmt = ] stmt

Containing Transact-SQL statements or batch of Unicode strings, stmt must be a Unicode constant or variable that can be implicitly converted to ntext . More complex Unicode expressions are not allowed (for example, use the + operator to concatenate two strings). Character constants are not allowed. If you specify a constant, you must use N as the prefix. For example, the Unicode constant N @ # sp_who @ # is valid, but the character constant @ # sp_who @ # is invalid. The size of the string is only limited by the available database server memory.

stmt can contain parameters in the same form as variable names, for example:

N@#SELECT * FROM Employees WHERE EmployeeID = @IDParameter@#

Each parameter contained in stmt must have a corresponding item in the @params parameter definition list and parameter value list.

[@params =] N@#@parameter_name data_type [,...n]@#

A string containing definitions of all parameters embedded in stmt . The string must be a Unicode constant or variable that can be implicitly converted to ntext . Each parameter definition consists of the parameter name and data type. n is a placeholder indicating additional parameter definition. Every parameter specified in stmt must be defined in @params . If the Transact-SQL statement or batch in stmt contains no parameters, @params is not required . The default value of this parameter is NULL.

[@param1 =] @#value1@#

The value of the first parameter defined in the parameter string. The value can be a constant or a variable. The parameter value must be provided for each parameter contained in stmt . If the Transact-SQL statement or batch included in stmt has no parameters, no value is required.

n

Placeholder for the value of additional parameters. These values ​​can only be constants or variables, not more complex expressions, such as functions or expressions generated using operators.

Return code value

0 (success) or 1 (failure)

Result set

Return a result set from all SQL statements that generate SQL strings.


Example (thanks to Zou Jian for providing)

declare @user varchar(1000)
declare @moTable varchar(20)
select @moTable = @#MT_10@#




declare @sql nvarchar(4000) --定义变量,注意类型
 

set @sql=@#select @user = count(distinct userid) from @#+@moTable --为变量赋值
 
--执行@sql中的语句
exec sp_executesql @sql
,N@#@user varchar(1000) out@# --表示@sql中的语句包含了一个输出参数
,@user out                   --和调用存储过程差不多,指定输出参数值
 
print @user


 

发布了18 篇原创文章 · 获赞 4 · 访问量 4万+

Guess you like

Origin blog.csdn.net/caoming51021/article/details/8086796
Recommended