2013-10-09 5 views
1

C# 응용 프로그램 용 SQL Server 데이터베이스에이 두 테이블이 있습니다.다른 테이블을 기반으로 SQL Server 테이블에 삽입

---------------------------- 
table_Items 
---------------------------- 
Item1 | Item2| Item3 | Item4 
A  | B | C  | D 
E  | F | G  | Null 
H  | I | Null | Null 
J  | Null | Null | Null 

------------------ 
table_Item_Shelves 
------------------ 
Item_Name | Item_ID 
A  | Null 
B  | Null 
C  | Null 
D  | Null 
E  | Null 

이것은 내가해야 할 일입니다. table_items의 각 행에 대해 row가 item_ID 필드의 각 항목에 대해 '1'을 삽입하는 것보다 table_item_Shelves에있는 의 모든 항목 (항목 1,2,3,4) 또는 세 항목에 값이 있는지 먼저 확인하십시오. 다음 행에 대해서는 같은 체크를 실시하고 Item_ID 필드에서 최대 값을 얻고 1 씩 증가시킵니다. 또한 최대 4 개의 Item_ID가 같을 수 있는지 확인해야합니다. C# 및 SQL에 도움이 될 것입니다. 감사.

table_Item_Shelves 열 ITEM_ID 이미 내가 새 ID table_Item_Shelves 이미 레코드를 포함 넣지 것보다 값이 있고, 내가 그 기록에 대한 업데이트해야합니다.

시저의 UpdateItemIDs가 AS rowIndex에, IT AS (항목 1 BY ORDER) 이상으로 SELECT ROW_NUMBER()를 BEGIN CREATE. * 0 (항목 1이 아닌 WHERE AS dbo.table_items IT FROM #TempTable INTO 처리 NULL AND 항목 2는 NULL이 아닌 항목 3은 AND ) NOT NULL이거나 (항목 1은 null이 아니고 항목 2는 NULL이 아닌 AND item4가 ) IS NULL NOT OR (항목 1은 null가 아니고, 항목 3은 null는 아니고, item4이 NULL NOT IS) OR (항목 2는 null가 아니고, 항목 3가 null가 아니고, item4이 NULL NOT IS) 내가 가지고있는

 DECLARE @ITEM1 VARCHAR(50) 
     DECLARE @ITEM2 VARCHAR(50) 
     DECLARE @ITEM3 VARCHAR(50) 
     DECLARE @ITEM4 VARCHAR(50) 
     DECLARE @RowIndex INT 
     DECLARE @NewItemID INT 

     WHILE (SELECT COUNT(*) 
       FROM #TempTable 
       WHERE processed = 0 
      ) > 0 
      BEGIN 
       SELECT TOP 1 
         @ITEM1 = Item1 , 
         @ITEM2 = Item2 , 
         @ITEM3 = item3 , 
         @ITEM4 = Item4 , 
         @RowIndex = RowIndex 
       FROM #TempTable 
       WHERE processed = 0 

       UPDATE #TempTable 
       SET  processed = 1 
       WHERE RowIndex = @RowIndex 

       SET @NewItemID = (SELECT ISNULL(MAX(Item_ID), 0) + 1 
            FROM  dbo.table_items_shelves 
           ) ; 

       UPDATE dbo.table_items_shelves 
       SET  Item_ID = @NewItemID 
       WHERE Item_Name IN (@ITEM1, @ITEM2, @ITEM3, @ITEM4) 
         AND Item_ID IS NULL 
      END 
    END 

이 위의 저장 프로 시저 (누군가의 도움을) 작동하지만, table_items (Item1, Item2 ..... Item8)의 8 열로 작동하도록 수정하고 행에 모두 값 (item1, item2 .... item8) 또는 5 개의 필드 중 table_Item_Shelves보다 이 Item_ID 필드의 각 항목에 대해 '1'을 삽입하십시오. 테이블 table_items에서 8 열 (항목 1, 항목 2 ..... Item8) 데이터에서 이제

able_Items 
----------------------------------------------------------------------- 
Item1 | Item2 | Item3  | Item4 | Item5 | Item6 | Item7 | Item8 | 
------------------------------------------------------------------------ 
Pencils | Rubbers | Books  | DvDs | Glue |Stapler| CDs |Mouse | 
Marker |KeyChain |Clipboards |Pens |Bucket| Null | 
Monitors| Null | 
Glue | Null |Null | Null | Null | Null | Null | Null | Null | 
Papers| Null | Null | Null 



table_Item_Shelves 
------------------ 
Item_Name | Item_ID 
------------------- 
Pencils | Null 
Rubbers | Null 
Pens  | Null 
Books  | Null 
Staplers | Null 
Glue  | Null 
Buckets | Null 
Keyborads | Null 
Monitors | Null 
Mouse  | Null 
CDs  | Null 
DvDs  | Null 
Papers | Null 
Clipboards| Null 
Markers | Null 
KeyChains | Null 

를 들어 내가이

table_Items 같은 결과 뭔가 행의 모든 ​​열에서 값이 예상 제공 1,

테이블에 Item_ID가 없으므로 1 행의 각 항목에 대해 '1'을 삽입합니다. 2 행을 검사보다는 각 항목에 대해, I 삽입한다 그래서, 5 개 개의 항목이 최대 (ITEM_ID) + 1

행 값 및 ROW 3+ ROW 3 < 5 및 행 4 < 5, 5 행 < 5 열 4 + ROW 5도 < 5이므로 무시합니다. 또한 "Item_ID"가 "NULL 또는 빈"이 아닌 경우 열을 무시합니다.

최종 결과는 다음과 같습니다.

table_Item_Shelves 
------------------ 
Item_Name | Item_ID 
------------------- 
Pencils | 1 
Rubbers | 1 
Pens  | 2 
Books  | 1 
Staplers | 1 
Glue  | 1 
Buckets | 2 
Keyborads | Null 
Monitors | Null 
Mouse  | 1 
CDs  | 1 
DvDs  | 1 
Papers | Null 
Clipboards| 2 
Markers | 2 
KeyChains | 2 

디자인 제안이 없습니다. 제 생각에 그것은 끔찍한 사실입니다. 감사.

+3

좀 더 일반적인 의미에서 도움이 될 수 있으므로 '데이터 정규화'를 읽어보십시오. 설계상의 결함이있는 것 같습니다 (제약 조건과 어플리케이션의보다 일반적인 상황을 이해하지 못한다면). –

+2

데이터가 어떤 모양인지 모르지만 내 머리 꼭대기에서 보면 꽤 펑키 한 디자인입니다. 한 열에서 8 열까지 최대 8 행까지 각각 하나의 값으로 뒤집으려고하는 것이 좋습니다. – Andrew

+1

@Andrew "디자인 제안이 만족스럽지 않습니다. 끔찍합니다. 감사합니다."전에이 글을 쓰는 것을 잊어 버렸습니다. 내가이 똑똑한 당신의 생각을 구현한다면 나는 여기 없었을거야. 당신의 도움을 주셔서 감사합니다. – mubi

답변

0

using System; 

    using System.Collections.Generic; 

    using System.Data; 

    using System.Data.SqlClient; 

    using System.Linq; 

    using System.Text; 


    namespace InsertTeamIdIntoTable 

    { 

     class Program 

     { 

      const string str = @"Data Source=(localdb)\Projects;Initial Catalog=TestDb;Integrated Security=SSPI"; 

      static void Main(string[] args) 

      { 


       InsertItemData(str); 

      } 


      private static void InsertItemData(string connectionString) 

      { 

       string queryString = 

        "SELECT item1,item2,item3,item4 FROM dbo.table_items;"; 


       using (SqlConnection connection = 

          new SqlConnection(connectionString)) 

       { 

        SqlCommand command = 

         new SqlCommand(queryString, connection); 

        connection.Open(); 


        SqlDataReader reader = command.ExecuteReader(); 

        int itemId = 1; 

        //check if row has values in all(item 1,2,3,4) or three of the fields, 

        while (reader.Read()) 

        { 

         bool flag = CheckValueNumber((IDataRecord)reader); 

         if (flag) 

         { 


          for (int i = 0; i < ((IDataRecord)reader).FieldCount; i++) 

          { 

           string itemName = ((IDataRecord)reader)[i].ToString(); 

           if (string.IsNullOrWhiteSpace(itemName) == false) 

           { 

            if (CheckItemShelveExists(str, itemName)) 

            { 

             if (CheckItemIdExists(str, itemName) == false) 

             { 

              UpdateTableItemShelves(str, itemId, itemName); 

             } 

            } 

            else 

            { 

             InsertTableItemShelves(str, itemId, itemName); 

            } 

           } 

          } 

          itemId++; 

         } 

        } 

        reader.Close(); 

       } 

      } 


      public static void UpdateTableItemShelves(string connectionString, int itemId, string itemName) 

      { 

       string updateString = string.Format("Update dbo.table_item_shelves set item_id ={0} WHERE item_name ='{1}';", itemId, itemName); 


       using (SqlConnection connection = 

          new SqlConnection(connectionString)) 

       { 

        SqlCommand command = 

         new SqlCommand(updateString, connection); 

        connection.Open(); 


        command.ExecuteNonQuery(); 


       } 

      } 


      public static void InsertTableItemShelves(string connectionString, int itemId, string itemName) 

      { 

       string updateString = string.Format("Insert Into dbo.table_item_shelves(item_id,item_name) VALUES({0},'{1}');", itemId, itemName); 


       using (SqlConnection connection = 

          new SqlConnection(connectionString)) 

       { 

        SqlCommand command = 

         new SqlCommand(updateString, connection); 

        connection.Open(); 


        command.ExecuteNonQuery(); 


       } 

      } 



      public static bool CheckItemShelveExists(string connectionString, string itemName) 

      { 

       string updateString = string.Format("Select count(id) From dbo.table_item_shelves WHERE item_name ='{0}';", itemName); 


       using (SqlConnection connection = 

          new SqlConnection(connectionString)) 

       { 

        SqlCommand command = 

         new SqlCommand(updateString, connection); 

        connection.Open(); 


        return (Int32)command.ExecuteScalar() > 0; 


       } 

      } 


      public static bool CheckItemIdExists(string connectionString, string itemName) 

      { 

       string updateString = string.Format("Select item_id From dbo.table_item_shelves WHERE item_name ='{0}';", itemName); 


       using (SqlConnection connection = 

          new SqlConnection(connectionString)) 

       { 

        SqlCommand command = 

         new SqlCommand(updateString, connection); 

        connection.Open(); 

        SqlDataReader reader = command.ExecuteReader(); 


        while (reader.Read()) 

        { 

         if (string.IsNullOrWhiteSpace(((IDataRecord)reader)[0].ToString()) == false) 

         { 

          return true; 

         } 

        } 


        reader.Close(); 

        return false; 


       } 

      } 


      public static bool CheckValueNumber(IDataRecord record) 

      { 

       int count = 0; 

       for (int i = 0; i < record.FieldCount; i++) 

       { 

        if (string.IsNullOrWhiteSpace(record[i].ToString()) == false) 

        { 

         count++; 

        } 

       } 

       return count >= 3; 

      } 


     } 

    } 
0

이 ... 원하는 최종 결과 (NO 예상 된 결과 예)하지만 클로스 더 쉽게 더 많은 필드를 다루는 극적으로 단순화 할 수 귀하의 절차의 첫 번째 부분을 이해하기 조금 어렵다

-- OLD 
WHERE (Item1 IS NOT NULL 
       AND Item2 IS NOT NULL 
       AND item3 IS NOT NULL 
      ) 
      OR (Item1 IS NOT NULL 
       AND Item2 IS NOT NULL 
       AND item4 IS NOT NULL 
       ) 
      OR (Item1 IS NOT NULL 
       AND Item3 IS NOT NULL 
       AND item4 IS NOT NULL 
       ) 
      OR (Item2 IS NOT NULL 
       AND Item3 IS NOT NULL 
       AND item4 IS NOT NULL 
       ) 

이 같은 다른 형식을 사용하여

이 형식은 그냥 CASE 문을 복제하고 유효한 필드의 수에 기준을 변경할 수 있습니다 (추가 데이터를 쿼리가 독립적으로 실행할 수 있도록하기 위해).

WITH A AS (
    SELECT 'A' AS Item1, 'B' AS Item2, 'C' AS Item3, 'D' AS Item4 
    UNION ALL SELECT 'E', 'F', 'G', NULL 
    UNION ALL SELECT 'H', 'I', NULL, NULL 
    UNION ALL SELECT 'J', NULL, NULL, NULL 
), B AS (
    SELECT A.* 
     , ROW_NUMBER() OVER (ORDER BY Item1) AS RowIndex 
     , 0 AS processed 
     , CASE WHEN Item1 IS NULL THEN 0 ELSE 1 END 
      + CASE WHEN Item2 IS NULL THEN 0 ELSE 1 END 
      + CASE WHEN Item3 IS NULL THEN 0 ELSE 1 END 
      + CASE WHEN Item4 IS NULL THEN 0 ELSE 1 END 
      AS ValidFieldCount 
    FROM A 
) 
SELECT * 
FROM B 
WHERE ValidFieldCount >=3 
+0

CASE 문을 하위 쿼리 대신 직접 where 절에 넣을 수도 있습니다. – DarrenMB

+0

좀 더 이해가되는지 확인하십시오. – mubi

+0

C#에서이 작업을 수행 할 수 있습니까? 만약 내가 각 행에 대한 배열을 만들 수있는 두 번째 테이블을 업데이 트하는 데 그 값을 사용하는 것보다? – mubi

관련 문제