PDA

View Full Version : قرار دادن چند دستور select در sqlcommand



amin1000
یک شنبه 04 مهر 1389, 13:12 عصر
سلام
شکل قرار دادن بیشتر از یک دستور select در sqlcommand به چه ترتیبی هست؟ چندین نمونه امتحان کردم خطا میگیره ...

navidiran
یک شنبه 04 مهر 1389, 13:58 عصر
ما نمی توانیم در یک CommandString چند تا دستور قراردهیم. (نه؟)
بهتر این هست که برای هر دستور ، string جداگانه در نظر بگیرید.

Jean Reno
یک شنبه 04 مهر 1389, 14:01 عصر
در این مثال که در یک Console اجرا شده از SqlDataReader استفاده شده است
مزیت این کلاس برای خوندن از بانک اینه که با دستور SqlDataReaderObj.NextResult(); می توان به جدول بعدی یعنی همون دستور Select بعدی دسترسی داشت




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string connectionString = @"Data Source=.\sql2005;Initial Catalog=AdventureWorks;Integrated Security=SSPI;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();

// our command text containing two select queries
string commandText = "SELECT ProductCategoryID, Name FROM [Production].[ProductCategory]; " +
"SELECT ProductSubcategoryID, Name FROM [Production].[ProductSubcategory]";
SqlCommand cmd = new SqlCommand(commandText, conn);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// look into categories result set
Console.WriteLine("Categories");
while (rdr.Read())
{
int categoryID = rdr.GetInt32(0);
string categoryName = rdr.GetString(1);
// NOTE: be careful when using indexes (as in above)
// make sure they match the order of columns in your select query

Console.WriteLine(categoryID + "\t" + categoryName);
}
// look into categories result set
rdr.NextResult();
// for separation in display only
Console.WriteLine(String.Empty.PadLeft(20, '-'));
Console.WriteLine("SubCategories");
while (rdr.Read())
{
int subCategoryID = rdr.GetInt32(0);
string subCategoryName = rdr.GetString(1);
Console.WriteLine(subCategoryID + "\t" + subCategoryName);
}
}
}
Console.ReadKey();
}
}
}