1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Retrieving a Single Value from a Query pdf

2 312 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Retrieving a single value from a query
Tác giả Team LiB
Thể loại Recipe
Định dạng
Số trang 2
Dung lượng 11,7 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

[ Team LiB ]Recipe 9.10 Retrieving a Single Value from a Query Problem Given a stored procedure that returns a single value, you need the fastest way to get this data.. Solution Use t

Trang 1

[ Team LiB ]

Recipe 9.10 Retrieving a Single Value from a Query

Problem

Given a stored procedure that returns a single value, you need the fastest way to get this data

Solution

Use the ExecuteScalar( ) method to return a single value from a stored procedure

The sample code uses the ExecuteScalar( ) method to get the number of records in the Orders table of the Northwind database

The C# code is shown in Example 9-13

Example 9-13 File: ExecuteScalarForm.cs

// Namespaces, variables, and constants

using System;

using System.Configuration;

using System.Data.SqlClient;

//

String sqlText = "SELECT COUNT(*) FROM Orders";

// Create the connection and the command

SqlConnection conn = new SqlConnection(

ConfigurationSettings.AppSettings["Sql_ConnectString"]);

SqlCommand cmd = new SqlCommand(sqlText, conn);

conn.Open( );

// Execute the scalar SQL statement and store results

int count = Convert.ToInt32(cmd.ExecuteScalar( ));

conn.Close( );

resultTextBox.Text="Count of Orders records: " + count;

Discussion

Trang 2

The ExecuteScalar( ) method of the Command object returns a single value from the data source rather than a table or data stream While the ExecuteScalar( ) method does not result in a performance improvement when compared to retrieving a single value using an output parameter or using a DataReader, it allows a single value to be returned with the least code and may therefore improve readability and maintainability

If the result set returns more than one result, the first column of the first row is returned

as a scalar value A null reference is returned if the result set is empty or if the result set

is a Ref Cursor when using the Oracle NET data provider

[ Team LiB ]

Ngày đăng: 14/12/2013, 18:16

TỪ KHÓA LIÊN QUAN

w