第一種情況:不帶輸出參數的
1編寫存儲過程
create procedure getsum
@n int =0
as
declare @sum int
declare @i int
set @sum=0
set @i=0
while @i<=@n begin
set @sum=@sum+@i
set @i=@i+1
end
print 'the sum is '+ltrim(rtrim(str(@sum)))
2.在SQL中執行測試存儲過程
exec getsum 100
3. 在JAVA中調用存儲過程(北京北大青鳥)
import java.sql.*;
public class ProcedureTest
{
public static void main(String args[]) throws Exception
{
//加載驅動
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
//獲得連接
Connection conn=DriverManager.getConnection("jdbc:odbc:mydata","sa","");
//創建存儲過程的對象
CallableStatement c=conn.divpareCall("{call getsum(?)}");
//給存儲過程的參數設置值
c.setInt(1,100); //將第一個參數的值設置成100
//執行存儲過程
c.execute();
conn.close();
}
}
第二種情況:帶輸出參數的(北京北大青鳥)
1.帶參數的帶輸出參數的
alter procedure getsum
@n int =0,
@result int output
as
declare @sum int
declare @i int
set @sum=0
set @i=0
while @i<=@n begin
set @sum=@sum+@i
set @i=@i+1
end
set @result=@sum
2.在查詢分析器中執行
declare @myResult int
exec getsum 100,@myResult output
print @myResult
3.在JAVA中調用
import java.sql.*;
public class ProcedureTest
{
public static void main(String args[]) throws Exception
{
//加載驅動
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
//獲得連接
Connection conn=DriverManager.getConnection("jdbc:odbc:mydata","sa","");
//創建存儲過程的對象
CallableStatement c=conn.divpareCall("{call getsum(?,?)}");
//給存儲過程的第一個參數設置值
c.setInt(1,100);
//注冊存儲過程的第二個參數
c.registerOutParameter(2,java.sql.Types.INTEGER);
//執行存儲過程
c.execute();
//得到存儲過程的輸出參數值
System.out.println (c.getInt(2));
conn.close();
}
}
(北京北大青鳥)