2013-04-13 209 views
0
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnnFinalProject"].ToString()); 
SqlCommand cmd = new SqlCommand(@"SELECT c.partID, p.name, p.categoryID, p.price, p.image, p.subCategoryID, 
             (CASE WHEN categoryID = 1 THEN 'Y' ELSE 'N' END) AS casesYN, 
             (CASE WHEN categoryID = 3 THEN 'Y' ELSE 'N' END) AS OSYN, 
             (CASE WHEN categoryID = 7 THEN 'Y' ELSE 'N' END) AS HDDYN, 
             (CASE WHEN subCategoryID = 1 THEN 'Y' ELSE 'N' END) AS powerYN, 
             (CASE WHEN subCategoryID = 2 THEN 'Y' ELSE 'N' END) AS processorYN, 
             (CASE WHEN subCategoryID = 3 THEN 'Y' ELSE 'N' END) AS moboYN, 
             (CASE WHEN subCategoryID = 4 THEN 'Y' ELSE 'N' END) AS memoryYN, 
             (CASE WHEN subCategoryID = 5 THEN 'Y' ELSE 'N' END) AS graphicsYN, 
             (CASE WHEN subCategoryID = 6 THEN 'Y' ELSE 'N' END) AS opticalYN, 
             (CASE WHEN subCategoryID = 7 THEN 'Y' ELSE 'N' END) AS soundYN 
             FROM configuration c JOIN parts p ON p.partID = c.partID 
             WHERE c.customID = @ID", conn); 
     conn.Open(); 
     SqlDataReader dr = cmd.ExecuteReader(); 
     while (dr.Read()) 
     { 
     string[] cases = { dr["partID"].ToString() }; 
     } 

如何插入到cases數組中只有'caseYN'值設置爲Y的partID,因爲它現在會在sql查詢中插入每個'partID'。從數據庫填充數組C#

回答

5

我認爲你不想改變你的SQL查詢。

使用List<string>而不是string[],因爲它會更容易添加新項目到它:循環結束後

var cases = new List<string>(); 
while (dr.Read()) 
{ 
    if(dr["casesYN"].ToString() == "Y") 
     cases.Add(dr["partID"].ToString()); 
} 

如果你真的需要一個數組,可以隨時撥打ToArray()方法:

string[] casesArray = cases.ToArray(); 

但它需要using System.Linq位於文件頂部。