概述 SQLServer -
存储过程基本
语法 博客分类: 数据库 oracle的建表sql转成sqlserver的建表sql时的注意点 : 1.所有的comment语句需要删除。 2.clob类型转换为text类型。 3.blob类型转换为image类型。 4.number类型转换为int,number(16,2)等转换为decimal(16,2),number(18)转换为bigint SQLServer - 存储过程基本语法
博客分类: 数据库
oracle的建表sql转成sqlserver的建表sql时的注意点 :
1.所有的comment语句需要删除。
2.clob类型转换为text类型。
3.blob类型转换为Image类型。
4.number类型转换为int,number(16,2)等转换为decimal(16,2),number(18)转换为bigint。
5.default sysdate改为default getDate()。
6.to_date('2009-12-18','yyyy-mm-dd')改为cast('2009-12-18' as datetime)
sqlSERVER:
变量的声明:
声明变量时必须在变量前加@符号
DECLARE @I INT
变量的赋值:
变量赋值时变量前必须加set
SET @I = 30
声明多个变量:
DECLARE @s varchar(10),@a INT
if语句:
Java代码
if .. begin ... end else if .. begin ... end else begin ... end if ..begin ...endelse if ..begin ...endelsebegin ...end
Example:
sql代码
DECLARE @d INT set @d = 1 IF @d = 1 BEGIN PRINT '正确' END ELSE BEGIN PRINT '错误' END DECLARE @d INTset @d = 1IF @d = 1 BEGIN PRINT '正确'ENDELSE BEGIN PRINT '错误'END
多条件选择语句:
Example:
sql代码
declare @today int declare @week nvarchar(3) set @today=3 set @week= case when @today=1 then '星期一' when @today=2 then '星期二' when @today=3 then '星期三' when @today=4 then '星期四' when @today=5 then '星期五' when @today=6 then '星期六' when @today=7 then '星期日' else '值错误' end print @week declare @today intdeclare @week nvarchar(3)set @today=3set @week= case when @today=1 then '星期一' when @today=2 then '星期二' when @today=3 then '星期三' when @today=4 then '星期四' when @today=5 then '星期五' when @today=6 then '星期六' when @today=7 then '星期日' else '值错误'endprint @week
循环语句:
Java代码
WHILE 条件 BEGIN 执行语句 END WHILE 条件 BEGIN 执行语句END
Example:
Java代码
DECLARE @i INT SET @i = 1 WHILE @i<1000000 BEGIN set @i=@i+1 END DECLARE @i INTSET @i = 1WHILE @i<1000000 BEGINset @i=@i+1END
定义游标:
sql代码
DECLARE @cur1 CURSOR FOR SELECT ......... OPEN @cur1 FETCH NEXT FROM @cur1 INTO 变量 WHILE(@@FETCH_STATUS=0) BEGIN 处理..... FETCH NEXT FROM @cur1 INTO 变量 END CLOSE @cur1 DEALLOCATE @cur1 DECLARE @cur1 CURSOR FOR SELECT .........OPEN @cur1FETCH NEXT FROM @cur1 INTO 变量WHILE(@@FETCH_STATUS=0)BEGIN处理.....FETCH NEXT FROM @cur1 INTO 变量ENDCLOSE @cur1DEALLOCATE @cur1
sql代码
AS declare @category_CI_tablename VARCHAR(50) ='' declare @result VARCHAR(2000) = '' declare @CI_ID DECIMAL = 0 declare @num int = 1 declare @countnum int = 1 BEGIN select @countnum = count(ATTRIBUTE_CONfig_ID) from T_ATTRIBUTE_CONfig where CMDB_UPDATE_FLAG= 'Y' and category_CODE =@category_CODE IF (@ATTRIBUTE2='A') begin DECLARE MyCursor CURSOR for select ATTRIBUTE_CONfig_CODE from T_ATTRIBUTE_CONfig where CMDB_UPDATE_FLAG= 'Y' and category_CODE =@category_CODE OPEN MyCursor FETCH NEXT FROM MyCursor INTO @CONfig_CODE set @result = @result+@CONfig_CODE+',' WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM MyCursor INTO @CONfig_CODE set @num = @num+ 1 if(@num<@countnum) begin set @result = @result+@CONfig_CODE+',' end else if(@num=@countnum) begin set @result = @result +@CONfig_CODE end END CLOSE MyCursor DEALLOCATE MyCursor set @result = 'insert into ' + @ATTRIBUTE1 + '(' + @result +') select '+ @result +' from '+@category_CI_tablename +' where CI_ORDER_liNE_ID='+@KEY_ID end else if((@ATTRIBUTE2='U')) ASdeclare @category_CI_tablename VARCHAR(50) =''declare @result VARCHAR(2000) = ''declare @CI_ID DECIMAL = 0declare @num int = 1declare @countnum int = 1BEGINselect @countnum = count(ATTRIBUTE_CONfig_ID) from T_ATTRIBUTE_CONfig where CMDB_UPDATE_FLAG= 'Y' and category_CODE =@category_CODE IF (@ATTRIBUTE2='A') begin DECLARE MyCursor CURSOR for select ATTRIBUTE_CONfig_CODE from T_ATTRIBUTE_CONfig where CMDB_UPDATE_FLAG= 'Y' and category_CODE =@category_CODE OPEN MyCursor FETCH NEXT FROM MyCursor INTO @CONfig_CODE set @result = @result+@CONfig_CODE+',' WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM MyCursor INTO @CONfig_CODE set @num = @num+ 1 if(@num<@countnum) begin set @result = @result+@CONfig_CODE+',' end else if(@num=@countnum) begin set @result = @result +@CONfig_CODE end END CLOSE MyCursor DEALLOCATE MyCursor set @result = 'insert into ' + @ATTRIBUTE1 + '(' + @result +') select '+ @result +' from '+@category_CI_tablename +' where CI_ORDER_liNE_ID='+@KEY_ID end else if((@ATTRIBUTE2='U'))
临时表:
-- Select INTO 从一个查询的计算结果中创建一个新表。 数据并不返回给客户端,这一点和普通的Select 不同。 新表的字段具有和 Select 的输出字段相关联(相同)的名字和数据类型。
select * into Newtable
from Uname
-- Insert INTO ABC Select
-- 表ABC必须存在
-- 把表Uname里面的字段Username复制到表ABC
Insert INTO ABC Select Username FROM Uname
-- 创建临时表
Create table #temp(
UID int IDentity(1,1) PRIMARY KEY,
Username varchar(16),
Pwd varchar(50),
Age smallint,
Sex varchar(6)
)
-- 打开临时表
Select * from #temp
1、局部临时表(#开头)只对当前连接有效,当前连接断开时自动删除。
2、全局临时表(##开头)对其它连接也有效,在当前连接和其他访问过它的连接都断开时自动删除。
3、不管局部临时表还是全局临时表,只要连接有访问权限,都可以用drop table #Tmp(或者drop table ##Tmp)来显式删除临时表。
临时表对执行效率应该影响不大,只要不是太过份,相反可以提高效率特别是连接查询的地方,只要你的数据库临时表空间足够
游标多,会严重执行效率,能免则免!
临时表在不同数据库设计中的作用
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 @H_7_1301@ @a int |
declare @H_7_1301@ @user1 nvarchar(50) |
select @H_7_1301@ @user1= '张三' |
declare @H_7_1301@ @user2 nvarchar(50) |
select @H_7_1301@ @user2 = name from @H_7_1301@ST_User where @H_7_1301@ ID=1 |
declare @H_7_1301@ @user3 nvarchar(50) |
update @H_7_1301@ ST_User set @H_7_1301@@user3 = name where @H_7_1301@ID=1 |
二、表、临时表、表变量
create table @H_7_1301@#DU_User1 |
@H_7_1301@[ID] [ int @H_7_1301@] NOT NulL @H_7_1301@, |
@H_7_1301@[OID] [ int @H_7_1301@] NOT NulL @H_7_1301@, |
@H_7_1301@[Login] [nvarchar](50) NOT NulL @H_7_1301@, |
@H_7_1301@[Rtx] [nvarchar](4) NOT NulL @H_7_1301@, |
@H_7_1301@[ name @H_7_1301@] [nvarchar](5) NOT NulL @H_7_1301@, |
@H_7_1301@[ Password @H_7_1301@] [nvarchar]( max @H_7_1301@) NulL @H_7_1301@, |
@H_7_1301@[State] [nvarchar](8) NOT NulL |
insert into @H_7_1301@#DU_User1 (ID,OID,[Login],Rtx, name @H_7_1301@,[ Password @H_7_1301@],State) values @H_7_1301@ (100,2, 'LS' @H_7_1301@, '0000' @H_7_1301@, '临时' @H_7_1301@, '321' @H_7_1301@, '特殊' @H_7_1301@ ); |
--从ST_User查询数据,填充至新生成的临时表 |
select @H_7_1301@ * into @H_7_1301@#DU_User2 from @H_7_1301@ST_User where @H_7_1301@ID<8 |
select @H_7_1301@ * from @H_7_1301@#DU_User2 where @H_7_1301@ID<3 union select @H_7_1301@* from @H_7_1301@#DU_User1 |
drop table @H_7_1301@#DU_User1 |
drop table @H_7_1301@#DU_User2 |
CREATE table @H_7_1301@#t |
@H_7_1301@[ID] [ int @H_7_1301@] NOT NulL @H_7_1301@, |
@H_7_1301@[OID] [ int @H_7_1301@] NOT NulL @H_7_1301@, |
@H_7_1301@[Login] [nvarchar](50) NOT NulL @H_7_1301@, |
@H_7_1301@[Rtx] [nvarchar](4) NOT NulL @H_7_1301@, |
@H_7_1301@[ name @H_7_1301@] [nvarchar](5) NOT NulL @H_7_1301@, |
@H_7_1301@[ Password @H_7_1301@] [nvarchar]( max @H_7_1301@) NulL @H_7_1301@, |
@H_7_1301@[State] [nvarchar](8) NOT NulL @H_7_1301@, |
insert into @H_7_1301@#t select @H_7_1301@* from @H_7_1301@ ST_User |
--select * into #t from dbo.ST_User |
alter table @H_7_1301@#t add @H_7_1301@[myID] int NOT NulL @H_7_1301@IDENTITY(1,1) |
alter table @H_7_1301@#t add @H_7_1301@[myID1] uniqueIDentifIEr NOT NulL default @H_7_1301@ (newID()) |
select @H_7_1301@ * from @H_7_1301@#t |
select @H_7_1301@ IDENTITY( int @H_7_1301@,1,1) as @H_7_1301@ID,name @H_7_1301@,[ Password @H_7_1301@] into @H_7_1301@ #t from @H_7_1301@ST_User |
select @H_7_1301@ * from @H_7_1301@#t |
select @H_7_1301@ ( select SUM @H_7_1301@(1) from @H_7_1301@ ST_User where @H_7_1301@ID<= a.ID) as @H_7_1301@myID,* from @H_7_1301@ST_User a order by @H_7_1301@myID |
declare @H_7_1301@ @t table |
@H_7_1301@ID int not null @H_7_1301@, |
@H_7_1301@msg nvarchar(50) null |
insert into @H_7_1301@@t values @H_7_1301@(1, '1' @H_7_1301@ ) |
insert into @H_7_1301@@t values @H_7_1301@(2, '2' @H_7_1301@ ) |
select @H_7_1301@ * from @H_7_1301@@t |
三、循环
declare @H_7_1301@ @a int |
declare @H_7_1301@ @ sum int |
set @H_7_1301@ @ sum @H_7_1301@=0 |
set @H_7_1301@@ sum @H_7_1301@ +=@a |
四、条件语句
declare @H_7_1301@ @today int |
declare @H_7_1301@ @week nvarchar(3) |
set @H_7_1301@ @week= case |
when @H_7_1301@@today=1 then '星期一' |
when @H_7_1301@@today=2 then '星期二' |
when @H_7_1301@@today=3 then '星期三' |
when @H_7_1301@@today=4 then '星期四' |
when @H_7_1301@@today=5 then '星期五' |
when @H_7_1301@@today=6 then '星期六' |
when @H_7_1301@@today=7 then '星期日' |
五、游标
declare @H_7_1301@ @ID int |
declare @H_7_1301@ @OID int |
declare @H_7_1301@ @Login varchar @H_7_1301@(50) |
declare @H_7_1301@ user_cur cursor for select @H_7_1301@ID,[Login] from @H_7_1301@ST_User |
@H_7_1301@while @@fetch_status=0 |
fetch next from @H_7_1301@ user_cur into @H_7_1301@@ID,@OID,@Login |
close @H_7_1301@ user_cur |
deallocate @H_7_1301@ user_cur |
六、触发器
触发器中的临时表:
Inserted
存放进行insert和update *** 作后的数据
Deleted
存放进行delete 和update *** 作前的数据
Create trigger @H_7_1301@User_OnUpdate |
declare @H_7_1301@@msg nvarchar(50) |
select @H_7_1301@@msg = N '姓名从“' @H_7_1301@ + Deleted. name @H_7_1301@+ N '”修改为“' @H_7_1301@+ Inserted. name @H_7_1301@+ '”' from @H_7_1301@Inserted,Deleted |
insert into @H_7_1301@[LOG](MSG) values @H_7_1301@(@msg) |
drop trigger @H_7_1301@User_OnUpdate |
七、存储过程
CREATE PROCEDURE @H_7_1301@PR_Sum |
@H_7_1301@@a int @H_7_1301@, |
@H_7_1301@@b int @H_7_1301@, |
@H_7_1301@@ sum int output |
set @H_7_1301@@ sum @H_7_1301@ =@a+@b |
CREATE PROCEDURE @H_7_1301@PR_Sum2 |
@H_7_1301@@a int @H_7_1301@, |
declare @H_7_1301@ @mysum int |
execute @H_7_1301@ PR_Sum 1,@mysum output |
declare @H_7_1301@ @mysum2 int |
execute @H_7_1301@ @mysum2= PR_Sum2 1,2 |
八、自定义函数
函数的分类:
1)标量值函数
2)表值函数
a:内联表值函数
b:多语句表值函数
3)系统函数
create function @H_7_1301@FUNC_Sum1 |
@H_7_1301@@a int @H_7_1301@, |
create function @H_7_1301@FUNC_UserTab_1 |
return @H_7_1301@ ( select @H_7_1301@* from @H_7_1301@ST_User where @H_7_1301@ID<@myID) |
create function @H_7_1301@FUNC_UserTab_2 |
returns @H_7_1301@ @t table |
@H_7_1301@[ID] [ int @H_7_1301@] NOT NulL @H_7_1301@, |
@H_7_1301@[OID] [ int @H_7_1301@] NOT NulL @H_7_1301@, |
@H_7_1301@[Login] [nvarchar](50) NOT NulL @H_7_1301@, |
@H_7_1301@[Rtx] [nvarchar](4) NOT NulL @H_7_1301@, |
@H_7_1301@[ name @H_7_1301@] [nvarchar](5) NOT NulL @H_7_1301@, |
@H_7_1301@[ Password @H_7_1301@] [nvarchar]( max @H_7_1301@) NulL @H_7_1301@, |
@H_7_1301@[State] [nvarchar](8) NOT NulL |
insert into @H_7_1301@@t select @H_7_1301@* from @H_7_1301@ ST_User where @H_7_1301@ID<@myID |
select @H_7_1301@ * from @H_7_1301@dbo.FUNC_UserTab_1(15) |
declare @H_7_1301@ @s int |
set @H_7_1301@ @s=dbo.FUNC_Sum1(100,50) |
drop function @H_7_1301@FUNC_Sum1 |
谈谈自定义函数与存储过程的区别:
一、自定义函数:
1. 可以返回表变量
2. 限制颇多,包括
不能使用output参数;
不能用临时表;
函数内部的 *** 作不能影响到外部环境;
不能通过select返回结果集;
不能update,delete,数据库表;
3. 必须return 一个标量值或表变量
自定义函数一般用在复用度高,功能简单单一,争对性强的地方。
二、存储过程
1. 不能返回表变量
2. 限制少,可以执行对数据库表的 *** 作,可以返回数据集
3. 可以return一个标量值,也可以省略return
存储过程一般用在实现复杂的功能,数据 *** 纵方面。
-----------------------------------------------------------------------------------------------------------------------------------
sqlServer存储过程--实例
实例1:只返回单一记录集的存储过程。
表银行存款表(bankMoney)的内容如下
ID | userID | Sex | Money |
001 | Zhangsan | 男 | 30 |
002 | Wangwu | 男 | 50 |
003 | Zhangsan | 男 | 40 |
要求1:查询表bankMoney的内容的存储过程
create procedure sp_query_bankMoney
as
select * from bankMoney
go
exec sp_query_bankMoney
注* 在使用过程中只需要把T-sql中的SQL语句替换为存储过程名,就可以了很方便吧!
实例2(向存储过程中传递参数):
加入一笔记录到表bankMoney,并查询此表中userID= Zhangsan的所有存款的总金额。
Create proc insert_bank @param1 char(10),@param2 varchar(20),@param3 varchar(20),@param4 int,@param5 int output
with encryption ---------加密
as
insert into bankMoney (ID,userID,sex,Money)
Values(@param1,@param2,@param3,@param4)
select @param5=sum(Money) from bankMoney where userID='Zhangsan'
go
在sql Server查询分析器中执行该存储过程的方法是:
declare @total_price int
exec insert_bank '004','Zhangsan','男',100,@total_price output
print '总余额为'+convert(varchar,@total_price)
go
在这里再啰嗦一下存储过程的3种传回值(方便正在看这个例子的朋友不用再去查看语法内容):
1.以Return传回整数
2.以output格式传回参数
3.Recordset
传回值的区别:
output和return都可在批次程式中用变量接收,而recordset则传回到执行批次的客户端中。
实例3:使用带有复杂 SELECT 语句的简单过程
下面的存储过程从四个表的联接中返回所有作者(提供了姓名)、出版的书籍以及出版社。该存储过程不使用任何参数。
USE pubs
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'au_info_all' AND type = 'P')
DROP PROCEDURE au_info_all
GO
CREATE PROCEDURE au_info_all
AS
SELECT au_lname,au_fname,Title,pub_name
FROM authors a INNER JOIN Titleauthor ta
ON a.au_ID = ta.au_ID INNER JOIN Titles t
ON t.Title_ID = ta.Title_ID INNER JOIN publishers p
ON t.pub_ID = p.pub_ID
GO
au_info_all 存储过程可以通过以下方法执行:
EXECUTE au_info_all
-- Or
EXEC au_info_all
如果该过程是批处理中的第一条语句,则可使用:
au_info_all
实例4:使用带有参数的简单过程
CREATE PROCEDURE au_info
@lastname varchar(40),
@firstname varchar(20)
AS
SELECT au_lname,pub_name
FROM authors a INNER JOIN Titleauthor ta
ON a.au_ID = ta.au_ID INNER JOIN Titles t
ON t.Title_ID = ta.Title_ID INNER JOIN publishers p
ON t.pub_ID = p.pub_ID
WHERE au_fname = @firstname
AND au_lname = @lastname
GO
au_info 存储过程可以通过以下方法执行:
EXECUTE au_info 'Dull','Ann'
-- Or
EXECUTE au_info @lastname = 'Dull',@firstname = 'Ann'
-- Or
EXECUTE au_info @firstname = 'Ann',@lastname = 'Dull'
-- Or
EXEC au_info 'Dull','Ann'
-- Or
EXEC au_info @lastname = 'Dull',@firstname = 'Ann'
-- Or
EXEC au_info @firstname = 'Ann',@lastname = 'Dull'
如果该过程是批处理中的第一条语句,则可使用:
au_info 'Dull','Ann'
-- Or
au_info @lastname = 'Dull',@firstname = 'Ann'
-- Or
au_info @firstname = 'Ann',@lastname = 'Dull'
实例5:使用带有通配符参数的简单过程 CREATE PROCEDURE au_info2 @lastname varchar(30) = 'D%', @firstname varchar(18) = '%' AS SELECT au_lname,pub_name FROM authors a INNER JOIN Titleauthor ta ON a.au_ID = ta.au_ID INNER JOIN Titles t ON t.Title_ID = ta.Title_ID INNER JOIN publishers p ON t.pub_ID = p.pub_ID WHERE au_fname liKE @firstname AND au_lname liKE @lastname GO au_info2 存储过程可以用多种组合执行。下面只列出了部分组合: EXECUTE au_info2 -- Or EXECUTE au_info2 'Wh%' -- Or EXECUTE au_info2 @firstname = 'A%' -- Or EXECUTE au_info2 '[CK]ars[OE]n' -- Or EXECUTE au_info2 'Hunter','Sheryl' -- Or EXECUTE au_info2 'H%','S%' = 'proc2' 实例6:if...else |
存储过程,其中@case作为执行update的选择依据,用if...else实现执行时根据传入的参数执行不同的修改.
--下面是if……else的存储过程:
if exists (select 1 from sysobjects where name = 'Student' and type ='u' )
drop table Student
go
if exists (select 1 from sysobjects where name = 'spUpdateStudent' and type ='p' )
drop proc spUpdateStudent
go
create table Student
(
fname nvarchar (10),
fAge
smallint,
fDiqu varchar (50),
fTel int
)
go
insert into Student values ('X.X.Y',28,'Tesing',888888)
go
create proc spUpdateStudent
(
@fCase int,
@fname nvarchar (10),
@fAge smallint,
@fDiqu varchar (50),
@fTel int
)
as
update Student
set fAge = @fAge,-- 传 1,3 都要更新 fAge 不需要用 case
fDiqu = (case when @fCase = 2 or @fCase = 3 then @fDiqu else fDiqu end ),
fTel = (case when @fCase = 3 then @fTel else fTel end )
where fname = @fname
select * from Student
go
-- 只改 Age
exec spUpdateStudent
@fCase = 1,
@fname = N'Update',
@fTel = 1010101
-- 改 Age 和 Diqu
exec spUpdateStudent
@fCase = 2,
@fTel = 1010101
-- 全改
exec spUpdateStudent
@fCase = 3,@fTel = 1010101
总结
以上是内存溢出为你收集整理的SQLServer - 存储过程基本语法全部内容,希望文章能够帮你解决SQLServer - 存储过程基本语法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
评论列表(0条)