儲存過程語法

qq34352631發表於2011-12-13

sql server

儲存過程語法

[@more@]

為了方便說明,資料庫使用SQL Server的示例資料庫,Northwindpubs,如果SQL Server中沒有的話,可以按下面的方法安裝

1,下載SQL2000SampleDb.msi,下載地址是:

-46A0-8DA2-EEBC53A68034&displaylang=en

2,安裝後,到預設目錄C:SQL Server 2000 Sample Databases instnwnd.sql instpubs.sql兩個檔案

3,在sql server中執行這兩個sql 就可以建立你Northwindpubs資料庫。

下面開始學T-SQL的語法

.註釋

-- 單行註釋,從這到本行結束為註釋,類似C++,c#//

/* … */ 多行註釋,類似C++C#/* … */

.變數(int, smallint, tinyint, decimal,float,real, money ,smallmoney, text ,image, char, varchar。。。。。。)

語法:

DECLARE

{

{@local_variable data_type}

} [,...n]

例如:

declare @ID int --申明一個名為@ID的變數,型別為int

.SQL Server視窗中列印出變數的值

語法:

PRINT 'any ASCII text' | @local_variable | @@FUNCTION | string_expr

.變數賦值

例如:

--從資料表中取出第一行資料的ID,賦值給變數@id,然後列印出來

Declare @ID int

Set @ID = (select top(1) categoryID from categories)

Print @ID

SQL中,我們不能像程式碼那樣直接給變數賦值,例如@id = 1,如果要達到這樣的功能,可以這樣寫:

Declare @ID int

Set @ID = (select 1) -- 類似 @ID=1

Select @id=1 -- 類似 @ID=1

Print @ID

.變數運算(+,-,*,/,……)

以下必要時候省略變數申明

Set @ID = (select 1+5) --類似 @ID=1+5

Set @ID=(select 1-@ID) --類似 @ID=1-@ID

.比較運算子

? > (greater than).

? < (less than).

? = (equals).

? <= (less than or equal to).

? >= (greater than or equal to).

? != (not equal to).

? <> (not equal to).

? ! < (not less than).

? !> (not greater than).

沒什麼說的

.語句塊:Begin … end

將多條語句作為一個塊,類似與C++C#中的{ }

例如:

Begin

Set @ID1 = (select 1)

Set @ID2 = (select 2)

End

.If if…else…

語法:

IF Boolean_expression

{sql_statement | statement_block}

[ELSE

{sql_statement | statement_block}]

例如:

If @id is not null

Print ‘@id is not null

if @ID = 1

begin

Set @ID = (select 1 + 1)

end

else

begin

set @ID=(select 1+2)

end

上面的例子用到了比較運算子,語句塊,和IF的語法。

.執行其他儲存過程 EXEC

例如

EXEC dbo.[Sales by Year] @Beginning_Date=’1/01/90’, @Ending_Date=’1/01/08’

.事務

語法:

BEGIN TRAN[SACTION] [transaction_name | @tran_name_variable]

例如

BEGIN TRAN

-- 做某些操作,例如Insert into …

if @@error <> 0

BEGIN

ROLLBACK TRAN

END

else

BEGIN

COMMIT TRAN

END

十一.遊標

我們可以在儲存過程中用Select語句取出每一行資料進行操作,這就需要用到遊標。

語法:

DECLARE cursor_name CURSOR

[LOCAL | GLOBAL]

[FORWARD_ONLY | SCROLL]

[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]

[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]

[TYPE_WARNING]

FOR select_statement

[FOR UPDATE [OF column_name [,...n]]]

例如:

DECLARE @au_id varchar(11), @au_fname varchar(20) –申明變數

--申明一個遊標

DECLARE authors_cursor CURSOR FOR

SELECT au_id, au_fname FROM authors

--開啟遊標

OPEN authors_cursor

--取出值

FETCH NEXT FROM authors_cursor INTO @au_id, @au_fname

--迴圈取出遊標的值

WHILE @@FETCH_STATUS = 0

BEGIN

Print @au_id

Print @au_fname

Print ‘ ’

FETCH NEXT FROM authors_cursor

INTO @au_id, @au_fname

END

CLOSE authors_cursor –關閉遊標

DEALLOCATE authors_cursor --釋放遊標

我覺得上面的是儲存過程常用的一些東東,如果要更深入的瞭解,更詳細的幫助,請參考SQL Server的幫助文件

例子:

我自己做了一個,沒有問題,你可以看一下
use Northwind
go
create proc test
@StartOrderID int,
@EndOrderID int,
@Code varchar(1000) Out
As
Begin
Declare @tmp int
Set @Code=''
Declare #cur_orders cursor for Select OrderID From Orders
where OrderID>=@startOrderID and OrderID<=@EndOrderID
for read only
Open #cur_Orders
fetch next from #cur_orders into @tmp
while @@fetch_Status=0
Begin
Set @Code=@Code+'-'+convert(varchar(8),@tmp)
fetch next from #cur_orders into @tmp
End
close #cur_Orders
Deallocate #cur_Orders
return

End
go

續2
String ret=null;
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String url
="jdbc:microsoft:sqlserver://192.168.0.102:1433;DatabaseName=Northwind";
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
CallableStatement stmt=conn.prepareCall("exec test ?,?,?");
stmt.setInt(1,10248);
stmt.setInt(2,10284);
stmt.registerOutParameter(3,Types.VARCHAR);
stmt.setString(3,ret);
stmt.execute();
System.out.println(stmt.getString(3));
stmt.close();
stmt=null;
conn.close();
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}

上面的例子沒有問題,針對你的情況,我又寫了一個,應該可以解決你現在的問題

-- 新建一個表
Create table tmpOrders (
OrderID int,
CustomerID nchar(5)
)

--把Orders 裡的OrderID列全部插入,這樣Orders與tmpOrders之間就是1:1關係了
insert into tmpOrders
Select distinct orderID,'tmp' from Orders

create proc test
@StartOrderID int,
@EndOrderID int,
@Code varchar(1000) Out
As
Begin
Declare @newOrderID int
Declare @newCustomerID nchar(5)
Declare @DummyInt int
Declare @DummyChar nchar(5)
Set @Code=''
/*
1:1
temp table/formal table is synchronized tmpOrders fetch from Orders, update tmpOrders
*/

-- for temp table
Declare #cur_tmpOrders Cursor for select OrderID,CustomerID
From tmpOrders
where OrderID>=@startOrderID
and OrderID<=@EndOrderID
for update

--for formal table
Declare #cur_orders cursor for Select OrderID,CustomerID
From Orders
where OrderID>=@startOrderID
and OrderID<=@EndOrderID
for read only
Open #cur_Orders
Open #cur_tmpOrders

fetch next from #cur_tmpOrders into @DummyInt,@dummyChar --Important!!!
fetch next from #cur_orders into @NewOrderID,@NewCustomerID
while @@fetch_Status=0
Begin
--Set @Code=@Code+'-'+convert(varchar(8),@NewOrderID)
--update tempOrders use corresponding Orders' data
Update tmpOrders set customerID=@newCustomerID
where current of #cur_tmpOrders
--pay attention to sequence of cursor fetch action!
fetch next from #cur_tmpOrders into @DummyInt,@dummyChar
if @@fetch_Status<>0 break; -- 沒有行了
fetch next from #cur_orders into @newOrderID,@NewCustomerID
End

close #cur_Orders
close #cur_tmpOrders

Deallocate #cur_Orders
Deallocate #cur_tmpOrders
Set @Code='Ok'
return

End

程式如下
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String url=
"jdbc:microsoft:sqlserver://192.168.0.102:1433;DatabaseName=Northwind";
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
CallableStatement stmt=conn.prepareCall("exec test ?,?,?");
stmt.setInt(1,10248);
stmt.setInt(2,10284);
stmt.registerOutParameter(3,Types.VARCHAR,1000);
stmt.setString(3,ret);
stmt.executeUpdate();
System.out.println(stmt.getString(3));
stmt.close();
stmt=null;
conn.close();
conn=null;
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/7646028/viewspace-1056815/,如需轉載,請註明出處,否則將追究法律責任。

相關文章