sql server的动态语句用法
--建立测试环境
IF OBJECT_ID('tb','U') IS NOT NULL DROP TABLE tb
GO
CREATE TABLE tb
(
id int identity,
code varchar(10),
name varchar(20),
CONSTRAINT PK_TB PRIMARY KEY (id)
)
GO
insert tb
select '001','财务部' union all
select '002','贸易部' union all
select '003','技术部' union all
select '004','市场部'
go
--动态语句1 得到结果集
declare @sql nvarchar(4000)
declare @wheresql varchar(1000)
set @wheresql=' and name=''技术部'''
set @sql = 'select * from tb where 1=1 '+ @wheresql
exec(@sql)
--结果
/*
id code name
----------- ---------- --------------------
3 003 技术部
*/
--动态语句2 输入输出参数
declare @ID int
set @sql = 'select @id=id from tb where name=@name '
exec sp_executesql @sql, N'@ID int output,@name varchar(20)',@ID output,'技术部'
select @ID
--结果
/*
-----------
3
*/
页:
[1]