SQLServer存储过程
--有输入参数的存储过程--
create proc GetComment
(@commentid int)
as
select * from Comment where CommentID=@commentid
--有输入与输出参数的存储过程--
create proc GetCommentCount
@newsid int,
@count int output
as
select @count=count(*) from Comment where NewsID=@newsid
--返回单个值的函数--
create function MyFunction
(@newsid int)
returns int
as
begin
declare @count int
select @count=count(*) from Comment where NewsID=@newsid
return @count
end
--调用方法--
declare @count int
exec @count=MyFunction 2
print @count
--返回值为表的函数--
Create function GetFunctionTable
(@newsid int)
returns table
as
return
(select * from Comment where NewsID=@newsid)
--返回值为表的函数的调用--
select * from GetFunctionTable(2)
-----------------------------------------------------------------------------------------------------------------------------------
SQLServer 存储过程中不拼接SQL字符串实现多条件查询
以前拼接的写法
set @sql=' select * from table where 1=1 '
if (@addDate is not null)
set @sql = @sql+' and addDate = '+ @addDate + ' '
if (@name <>'' and is not null)
set @sql = @sql+ ' and name = ' + @name + ' '
exec(@sql)
下面是 不采用拼接SQL字符串实现多条件查询的解决方案
第一种写法是 感觉代码有些冗余
if (@addDate is not null) and (@name <> '')
select * from table where addDate = @addDate and name = @name
else if (@addDate is not null) and (@name ='')
select * from table where addDate = @addDate
else if(@addDate is null) and (@name <> '')
select * from table where and name = @name
else if(@addDate is null) and (@name = '')
select * from table
第二种写法是
select * from table where (addDate = @addDate or @addDate is null) and (name = @name or @name = '')
第三种写法是
SELECT * FROM table where
addDate = CASE @addDate IS NULL THEN addDate ELSE @addDate END,
name = CASE @name WHEN '' THEN name ELSE @name END
-----------------------------------------------------------------------------------------------------------------------------------
SQLSERVER存储过程基本语法
一、定义变量
--简单赋值
declare @a int
set @a=5
print @a
--使用select语句赋值
declare @user1 nvarchar(50)
select @user1= '张三'
print @user1
declare @user2 nvarchar(50)
select @user2 = Name from ST_User where ID=1
print @user2
--使用update语句赋值
declare @user3 nvarchar(50)
update ST_User set @user3 = Name where ID=1
print @user3
二、表、临时表、表变量
--创建临时表1
create table #DU_User1
(
[ID] [ int ] NOT NULL ,
[Oid] [ int ] NOT NULL ,
[Login] [nvarchar](50) NOT NULL ,
[Rtx] [nvarchar](4) NOT NULL ,
[ Name ] [nvarchar](5) NOT NULL ,
[ Password ] [nvarchar]( max ) NULL ,
[State] [nvarchar](8) NOT NULL
);
--向临时表1插入一条记录
insert in
- 发表评论
-
- 最新评论 更多>>