使用 XmlReader 检索 XML 数据
创建一个 SqlCommand 对象来调用可生成 XML 结果集的存储过程(例如在 SELECT 语句中使用 FOR XML 子句)将该 SqlCommand 对象与某个连接相关联
调用 SqlCommand 对象的 ExecuteXmlReader 方法并且将结果分配给只进 XmlTextReader 对象当您不需要对返回的数据进行任何基于 XML 的验证时这是应该使用的最快类型的 XmlReader 对象
使用 XmlTextReader 对象的 Read 方法来读取数据
如何使用存储过程输出参数来检索单个行
借助于命名的输出参数可以调用在单个行内返回检索到的数据项的存储过程以下代码片段使用存储过程来检索 Northwind 数据库的 Products 表中包含的特定产品的产品名称和单价
void GetProductDetails( int ProductID
out string ProductName out decimal UnitPrice )
{
using( SqlConnection conn = new SqlConnection(
server=(local);Integrated Security=SSPI;database=Northwind) )
{
// Set up the command object used to execute the stored proc
SqlCommand cmd = new SqlCommand( DATGetProductDetailsSPOutput conn )
cmdCommandType = CommandTypeStoredProcedure;
// Establish stored proc parameters
// @ProductID int INPUT
// @ProductName nvarchar() OUTPUT
// @UnitPrice money OUTPUT
// Must explicitly set the direction of output parameters
SqlParameter paramProdID =
cmdParametersAdd( @ProductID ProductID );
paramProdIDDirection = ParameterDirectionInput;
SqlParameter paramProdName =
cmdParametersAdd( @ProductName SqlDbTypeVarChar );
paramProdNameDirection = ParameterDirectionOutput;
SqlParameter paramUnitPrice =
cmdParametersAdd( @UnitPrice SqlDbTypeMoney );
paramUnitPriceDirection = ParameterDirectionOutput;
connOpen();
// Use ExecuteNonQuery to run the command
// Although no rows are returned any mapped output parameters
// (and potentially return values) are populated
cmdExecuteNonQuery( );
// Return output parameters from stored proc
ProductName = paramProdNameValueToString();
UnitPrice = (decimal)paramUnitPriceValue;
}
}
使用存储过程输出参数来检索单个行
创建一个 SqlCommand 对象并将其与一个 SqlConnection 对象相关联
通过调用 SqlCommand 的 Parameters 集合的 Add 方法来设置存储过程参数默认情况下参数都被假设为输入参数因此必须显式设置任何输出参数的方向
注 一种良好的习惯做法是显式设置所有参数(包括输入参数)的方向
打开连接
调用 SqlCommand 对象的 ExecuteNonQuery 方法这将填充输出参数(并可能填充返回值)
通过使用 Value 属性从适当的 SqlParameter 对象中检索输出参数
关闭连接
[] [] [] [] [] [] [] [] []