create procedure datretrieveproductsxml
as
select * from products
for xml auto
go
使用 xmlreader 檢索 xml 資料
1. 建立一個 sqlcommand 對象來調用可產生 xml 結果集的預存程序(例如,在 select 語句中使用 for xml 子句)。將該 sqlcommand 對象與某個串連相關聯。
2. 調用 sqlcommand 對象的 executexmlreader 方法,並且將結果分配給只進 xmltextreader 對象。當您不需要對返回的資料進行任何基於 xml 的驗證時,這是應該使用的最快類型的 xmlreader 對象。
3. 使用 xmltextreader 對象的 read 方法來讀取資料。
如何使用預存程序輸出參數來檢索單個行
藉助於命名的輸出參數,可以調用在單個行內返回檢索到的資料項目的預存程序。以下程式碼片段使用預存程序來檢索 northwind 資料庫教程的 products 表中包含的特定產品的產品名稱和單價。
1 void getproductdetails( int productid,
2 out string productname, out decimal unitprice )
3 {
4 using( sqlconnection conn = new sqlconnection(
5 "server=(local);integrated security=sspi;database=northwind") )
6 {
7 // set up the command object used to execute the stored proc
8 sqlcommand cmd = new sqlcommand( "datgetproductdetailsspoutput", conn )
9 cmd.commandtype = commandtype.storedprocedure;
10 // establish stored proc parameters.
11 // @productid int input
12 // @productname nvarchar(40) output
13 // @unitprice money output
14
15 // must explicitly set the direction of output parameters
16 sqlparameter paramprodid =
17 cmd.parameters.add( "@productid", productid );
18 paramprodid.direction = parameterdirection.input;
19 sqlparameter paramprodname =
20 cmd.parameters.add( "@productname", sqldbtype.varchar, 40 );
21 paramprodname.direction = parameterdirection.output;
22 sqlparameter paramunitprice =
23 cmd.parameters.add( "@unitprice", sqldbtype.money );
24 paramunitprice.direction = parameterdirection.output;
25
26 conn.open();
27 // use executenonquery to run the command.
28 // although no rows are returned any mapped output parameters
29 // (and potentially return values) are populated
30 cmd.executenonquery( );
31 // return output parameters from stored proc
32 productname = paramprodname.value.tostring();
33 unitprice = (decimal)paramunitprice.value;
34 }
35 }
使用預存程序輸出參數來檢索單個行
1. 建立一個 sqlcommand 對象並將其與一個 sqlconnection 對象相關聯。
2. 通過調用 sqlcommand 的 parameters 集合的 add 方法來設定預存程序參數。預設情況下,參數都被假設為輸入參數,因此必須顯式設定任何輸出參數的方向。
注 一種良好的習慣做法是顯式設定所有參數(包括輸入參數)的方向。
3. 開啟串連。
4. 調用 sqlcommand 對象的 executenonquery 方法。這將填充輸出參數(並可能填充傳回值)。
5. 通過使用 value 屬性,從適當的 sqlparameter 對象中檢索輸出參數。
6. 關閉串連。
上述程式碼片段調用了以下預存程序。
1 create procedure datgetproductdetailsspoutput
2 @productid int,
3 @productname nvarchar(40) output,
4 @unitprice money output
5 as
6 select @productname = productname,
7 @unitprice = unitprice
8 from products
9 where productid = @productid
10 go