CREATE PROC [ EDURE ] procedure_name [ ; number ]
[ { @parameter data_type }
[ VARYING ] [ = default ] [ OUTPUT ]
] [ ,...n ]
[ WITH
{ RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ]
[ FOR REPLICATION ]
AS sql_statement [ ...n ]
@parameter
過程中的參數。在 Create PROCEDURE 語句中可以聲明一個或多個參數。用戶必須在執行過程時提供每個所聲明參數的值(除非定義了該參數的默認值)。
OUTPUT
表明參數是返回參數。該選項的值可以返回給 EXEC[UTE]。使用 OUTPUT 參數可將信息返回給調用過程。Text、ntext 和 image 參數可用作 OUTPUT 參數。使用 OUTPUT 關鍵字的輸出參數可以是游標占位符。
AS :指定過程要執行的操作
SQLSERVER:
變量的聲明:
聲明變量時必須在變量前加@符號
DECLARE @I INT
變量的賦值:
變量賦值時變量前必須加set
SET @I = 30
聲明多個變量:
DECLARE @s varchar(10),@a INT
----------------------------------------------------------------------------------------
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語句:
- if ..
- begin
- ...
- end
- else if ..
- begin
- ...
- end
- else
- begin
- ...
- end
Example:
- DECLARE @d INT
- set @d = 1
- IF @d = 1 BEGIN
- PRINT '正確'
- END
- ELSE BEGIN
- PRINT '錯誤'
- END
多條件選擇語句:
Example:
- 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
循環語句:
- WHILE 條件 BEGIN
- 執行語句
- END
Example:
- DECLARE @i INT
- SET @i = 1
- WHILE @i<1000000 BEGIN
- set @i=@i+1
- END
定義游標:
- 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
- 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'))
臨時表:
-- 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)來顯式刪除臨時表。
臨時表對執行效率應該影響不大,只要不是太過份,相反可以提高效率特別是連接查詢的地方,只要你的數據庫臨時表空間足夠
游標多,會嚴重執行效率,能免則免!
===============================================================================
其他:
--有輸入參數的存儲過程--
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 into #DU_User1 (ID,Oid,[Login],Rtx, Name ,[ Password ],State) values (100,2, 'LS' ,'0000' , '臨時' , '321' , '特殊' ); |
|
--從ST_User查詢數據,填充至新生成的臨時表 |
select * into #DU_User2 from ST_User where ID<8 |
|
--查詢並聯合兩臨時表 |
select * from #DU_User2 where ID<3 union select * from #DU_User1 |
|
--刪除兩臨時表 |
drop table #DU_User1 |
drop table #DU_User2 |
--創建臨時表 |
CREATE TABLE #t |
( |
[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 , |
) |
|
--將查詢結果集(多條數據)插入臨時表 |
insert into #t select * from ST_User |
--不能這樣插入 |
--select * into #t from dbo.ST_User |
|
--添加一列,為int型自增長子段 |
alter table #t add [myid] int NOT NULL IDENTITY(1,1) |
--添加一列,默認填充全球唯一標識 |
alter table #t add [myid1] uniqueidentifier NOT NULL default (newid()) |
|
select * from #t |
drop table #t |
--給查詢結果集增加自增長列 |
|
--無主鍵時: |
select IDENTITY( int ,1,1) as ID, Name ,[Login],[ Password ] into #t from ST_User |
select * from #t |
|
--有主鍵時: |
select ( select SUM (1) from ST_User where ID<= a.ID) as myID,* from ST_User a order bymyID |
--定義表變量 |
declare @t table |
( |
id int not null , |
msg nvarchar(50) null |
) |
insert into @t values (1, '1' ) |
insert into @t values (2, '2' ) |
select * from @t |
三、循環
--while循環計算1到100的和 |
declare @a int |
declare @ sum int |
set @a=1 |
set @ sum =0 |
while @a<=100 |
begin |
set @ sum +=@a |
set @a+=1 |
end |
print @ sum |
四、條件語句
--if,else條件分支 |
if(1+1=2) |
begin |
print '對' |
end |
else |
begin |
print '錯' |
end |
|
--when then條件分支 |
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 @ID int |
declare @Oid int |
declare @Login varchar (50) |
|
--定義一個游標 |
declare user_cur cursor for select ID,Oid,[Login] from ST_User |
--打開游標 |
open user_cur |
while @@fetch_status=0 |
begin |
--讀取游標 |
fetch next from user_cur into @ID,@Oid,@Login |
print @ID |
--print @Login |
end |
close user_cur |
--摧毀游標 |
deallocate user_cur |
六、觸發器
觸發器中的臨時表:
Inserted
存放進行insert和update 操作后的數據
Deleted
存放進行delete 和update操作前的數據
--創建觸發器 |
Create trigger User_OnUpdate |
On ST_User |
for Update |
As |
declare @msg nvarchar(50) |
--@msg記錄修改情況 |
select @msg = N '姓名從“' + Deleted. Name + N '”修改為“' + Inserted. Name + '”' fromInserted,Deleted |
--插入日志表 |
insert into [LOG](MSG) values (@msg) |
|
--刪除觸發器 |
drop trigger User_OnUpdate |
七、存儲過程
--創建帶output參數的存儲過程 |
CREATE PROCEDURE PR_Sum |
@a int , |
@b int , |
@ sum int output |
AS |
BEGIN |
set @ sum =@a+@b |
END |
|
--創建Return返回值存儲過程 |
CREATE PROCEDURE PR_Sum2 |
@a int , |
@b int |
AS |
BEGIN |
Return @a+@b |
END |
|
--執行存儲過程獲取output型返回值 |
declare @mysum int |
execute PR_Sum 1,2,@mysum output |
print @mysum |
|
--執行存儲過程獲取Return型返回值 |
declare @mysum2 int |
execute @mysum2= PR_Sum2 1,2 |
print @mysum2 |
八、自定義函數
函數的分類:
1)標量值函數
2)表值函數
a:內聯表值函數
b:多語句表值函數
3)系統函數
--新建標量值函數 |
create function FUNC_Sum1 |
( |
@a int , |
@b int |
) |
returns int |
as |
begin |
return @a+@b |
end |
|
--新建內聯表值函數 |
create function FUNC_UserTab_1 |
( |
@myId int |
) |
returns table |
as |
return ( select * from ST_User where ID<@myId) |
|
--新建多語句表值函數 |
create function FUNC_UserTab_2 |
( |
@myId int |
) |
returns @t table |
( |
[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 |
) |
as |
begin |
insert into @t select * from ST_User where ID<@myId |
return |
end |
|
--調用表值函數 |
select * from dbo.FUNC_UserTab_1(15) |
--調用標量值函數 |
declare @s int |
set @s=dbo.FUNC_Sum1(100,50) |
print @s |
|
--刪除標量值函數 |
drop function 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, 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
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 au_info2 存儲過程可以用多種組合執行。下面只列出了部分組合: EXECUTE au_info2 = '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,2,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'X.X.Y' ,
@fAge = 80,
@fDiqu = N'Update' ,
@fTel = 1010101
-- 改 Age 和 Diqu
exec spUpdateStudent
@fCase = 2,
@fName = N'X.X.Y' ,
@fAge = 80,
@fDiqu = N'Update' ,
@fTel = 1010101
-- 全改
exec spUpdateStudent
@fCase = 3,
@fName = N'X.X.Y' ,
@fAge = 80,
@fDiqu = N'Update' ,
@fTel = 1010101

