выбрать один столбец из ИСКЛЮЧЕНИЯ результата - PullRequest
0 голосов
/ 10 марта 2011

Я просто хочу ItemID из результата этого оператора EXCEPT:

SELECT     ManufacturerID, ItemID, ItemName, Description, Notes, Dimensions, BasePrice, SpecialPrice, OrderMinimumQuantity, OrderMultipleQuantity, 
                      OnHandQuantity, Category, IntroDate, BackOrderDate, UPC, PriceLevel1, PriceLevel2, PriceLevel3, PriceLevel4, PriceLevel5, PriceLevel6, PriceLevel7, PriceLevel8, 
                      PriceLevel9, PieceBox, Cubes, UnitOfMeasure, UDF1, UDF2, UDF3, UDF4, UDF5, AdditionalImageCount, PhotoName, AppendProductModifiers, Discontinued, 
                      IsDeleted
FROM         StagingProducts
WHERE     (ManufacturerID = 10)
EXCEPT 
SELECT     ManufacturerID, ItemID, ItemName, Description, Notes, Dimensions, BasePrice, SpecialPrice, OrderMinimumQuantity, OrderMultipleQuantity, 
                      OnHandQuantity, Category, IntroDate, BackOrderDate, UPC, PriceLevel1, PriceLevel2, PriceLevel3, PriceLevel4, PriceLevel5, PriceLevel6, PriceLevel7, PriceLevel8, 
                      PriceLevel9, PieceBox, Cubes, UnitOfMeasure, UDF1, UDF2, UDF3, UDF4, UDF5, AdditionalImageCount, PhotoName, AppendProductModifiers, Discontinued, 
                      IsDeleted
FROM         Products
WHERE     (ManufacturerID = 10)

Что было бы действительно хорошо, если бы я мог сохранить результаты оператора EXCEPT для использования в запросе INSERT INTO ниже по строке.

По сути, я собираюсь удалить записи, основанные на возврате ItemID из этого оператора EXCEPT из таблицы Products, а затем вставить новые записи, которые являются результатом того же оператора EXCEPT, - со старым входом и новым.

ОБНОВЛЕНИЕ - рабочий раствор:

    DECLARE @T TABLE (
    [ManufacturerID] [int] NOT NULL,
    [ItemID] [nvarchar](50) NULL,
    [ItemName] [nvarchar](100) NOT NULL,
    [Description] [nvarchar](max) NULL,
    [Notes] [nvarchar](200) NULL,
    [Dimensions] [nvarchar](50) NULL,
    [BasePrice] [money] NOT NULL,
    [SpecialPrice] [money] NULL,
    [OrderMinimumQuantity] [int] NOT NULL,
    [OrderMultipleQuantity] [int] NOT NULL,
    [OnHandQuantity] [int] NULL,
    [Category] [nvarchar](100) NULL,
    [IntroDate] [date] NULL,
    [BackOrderDate] [date] NULL,
    [UPC] [nvarchar](25) NULL,
    [PriceLevel1] [decimal](18, 0) NULL,
    [PriceLevel2] [decimal](18, 0) NULL,
    [PriceLevel3] [decimal](18, 0) NULL,
    [PriceLevel4] [decimal](18, 0) NULL,
    [PriceLevel5] [decimal](18, 0) NULL,
    [PriceLevel6] [decimal](18, 0) NULL,
    [PriceLevel7] [decimal](18, 0) NULL,
    [PriceLevel8] [decimal](18, 0) NULL,
    [PriceLevel9] [decimal](18, 0) NULL,
    [PieceBox] [int] NULL,
    [Cubes] [decimal](18, 0) NULL,
    [UnitOfMeasure] [nvarchar](10) NULL,
    [UDF1] [nvarchar](50) NULL,
    [UDF2] [nvarchar](50) NULL,
    [UDF3] [nvarchar](50) NULL,
    [UDF4] [nvarchar](50) NULL,
    [UDF5] [nvarchar](50) NULL,
    [AdditionalImageCount] [smallint] NULL,
    [PhotoName] [nvarchar](50) NULL,
    [AppendProductModifiers] [bit] NULL,
    [Discontinued] [bit] NULL,
    [IsDeleted] [bit] NOT NULL)

;WITH T As
(SELECT     ManufacturerID, ItemID, ItemName, Description, Notes, Dimensions, BasePrice, SpecialPrice, OrderMinimumQuantity, OrderMultipleQuantity, 
                      OnHandQuantity, Category, IntroDate, BackOrderDate, UPC, PriceLevel1, PriceLevel2, PriceLevel3, PriceLevel4, PriceLevel5, PriceLevel6, PriceLevel7, PriceLevel8, 
                      PriceLevel9, PieceBox, Cubes, UnitOfMeasure, UDF1, UDF2, UDF3, UDF4, UDF5, AdditionalImageCount, PhotoName, AppendProductModifiers, Discontinued, 
                      IsDeleted
FROM         StagingProducts
WHERE     (ManufacturerID = @ManufacturerID)
EXCEPT 
SELECT     ManufacturerID, ItemID, ItemName, Description, Notes, Dimensions, BasePrice, SpecialPrice, OrderMinimumQuantity, OrderMultipleQuantity, 
                      OnHandQuantity, Category, IntroDate, BackOrderDate, UPC, PriceLevel1, PriceLevel2, PriceLevel3, PriceLevel4, PriceLevel5, PriceLevel6, PriceLevel7, PriceLevel8, 
                      PriceLevel9, PieceBox, Cubes, UnitOfMeasure, UDF1, UDF2, UDF3, UDF4, UDF5, AdditionalImageCount, PhotoName, AppendProductModifiers, Discontinued, 
                      IsDeleted
FROM         Products
WHERE     (ManufacturerID = @ManufacturerID)
)
INSERT INTO  @T
SELECT * 
FROM T

    -- Kill the old products
    Delete FROM Products where ManufacturerID = @ManufacturerID
        AND ItemID IN(SELECT ItemID FROM @T)

    -- insert the new products  
    INSERT INTO Products ([ManufacturerID]
           ,[ItemID]
           ,[ItemName]
           ,[Description]
           ,[Notes]
           ,[Dimensions]
           ,[BasePrice]
           ,[SpecialPrice]
           ,[OrderMinimumQuantity]
           ,[OrderMultipleQuantity]
           ,[OnHandQuantity]
           ,[Category]
           ,[IntroDate]
           ,[BackOrderDate]
           ,[UPC]
           ,[PriceLevel1]
           ,[PriceLevel2]
           ,[PriceLevel3]
           ,[PriceLevel4]
           ,[PriceLevel5]
           ,[PriceLevel6]
           ,[PriceLevel7]
           ,[PriceLevel8]
           ,[PriceLevel9]
           ,[PieceBox]
           ,[Cubes]
           ,[UnitOfMeasure]
           ,[UDF1]
           ,[UDF2]
           ,[UDF3]
           ,[UDF4]
           ,[UDF5]
           ,[AdditionalImageCount]
           ,[PhotoName]
           ,[AppendProductModifiers]
           ,[Discontinued]
           ,[CreatedOn]
           ,[CreatedBy]
           ,[ModifiedOn]
           ,[ModifiedBy]
           ,[DeletedOn]
           ,[DeletedBy]
           ,[IsDeleted])
    SELECT [ManufacturerID]
      ,[ItemID]
      ,[ItemName]
      ,[Description]
      ,[Notes]
      ,[Dimensions]
      ,[BasePrice]
      ,[SpecialPrice]
      ,[OrderMinimumQuantity]
      ,[OrderMultipleQuantity]
      ,[OnHandQuantity]
      ,[Category]
      ,[IntroDate]
      ,[BackOrderDate]
      ,[UPC]
      ,[PriceLevel1]
      ,[PriceLevel2]
      ,[PriceLevel3]
      ,[PriceLevel4]
      ,[PriceLevel5]
      ,[PriceLevel6]
      ,[PriceLevel7]
      ,[PriceLevel8]
      ,[PriceLevel9]
      ,[PieceBox]
      ,[Cubes]
      ,[UnitOfMeasure]
      ,[UDF1]
      ,[UDF2]
      ,[UDF3]
      ,[UDF4]
      ,[UDF5]
      ,[AdditionalImageCount]
      ,[PhotoName]
      ,[AppendProductModifiers]
      ,[Discontinued]
      ,[CreatedOn]
      ,[CreatedBy]
      ,[ModifiedOn]
      ,[ModifiedBy]
      ,[DeletedOn]
      ,[DeletedBy]
      ,[IsDeleted] from StagingProducts
      Where ManufacturerID = @ManufacturerID
      AND ItemID IN(SELECT ItemID FROM @T)

Ответы [ 3 ]

2 голосов
/ 10 марта 2011

Поскольку вы работаете в SQL Server 2008, возможно, вы захотите узнать MERGE о ваших потребностях в синхронизации, но чтобы ответить на заданный вопрос, вы можете сделать

DECLARE @T TABLE (ItemID INT PRIMARY KEY)

;WITH T As
(
Your Big Statement
)
INSERT INTO  @T
SELECT ItemID 
FROM T
1 голос
/ 11 марта 2011

Забудьте CTE и табличную переменную: просто используйте MERGE.

CTE просто делает то, что WHEN [NOT] MATCH часть MERGE все равно делает.

У вас уже естьпромежуточная таблица (StagingProducts), поэтому вам не нужно @T.

MERGE будет выглядеть примерно так (я сократил список столбцов с помощью ...):

MERGE INTO Products
USING StagingProducts
   ON Products.ManufacturerID = StagingProducts.ManufacturerID
      AND Products.ItemID = StagingProducts.ItemID
      AND Products.ManufacturerID = @ManufacturerID
WHEN MATCHED THEN
   UPDATE 
      SET ItemName = StagingProducts.ItemName, 
          Description = StagingProducts.Description, 
          Notes = StagingProducts.Notes, 
          ...
          IsDeleted = StagingProducts.IsDeleted 
WHEN NOT MATCHED THEN
   INSERT (ManufacturerID, ItemID, ItemName, Description, Notes, ..., IsDeleted)
      VALUES (ManufacturerID, ItemID, ItemName, Description, Notes, ..., IsDeleted);
1 голос
/ 10 марта 2011

Отдельно от ответа Мартина об использовании MERGE ...

Вы можете использовать NOT EXISTS, который дает тот же план запроса и более читабелен.

SELECT     ManufacturerID, ItemID, ItemName, Description, Notes, Dimensions, BasePrice, SpecialPrice, OrderMinimumQuantity, OrderMultipleQuantity, 
                      OnHandQuantity, Category, IntroDate, BackOrderDate, UPC, PriceLevel1, PriceLevel2, PriceLevel3, PriceLevel4, PriceLevel5, PriceLevel6, PriceLevel7, PriceLevel8, 
                      PriceLevel9, PieceBox, Cubes, UnitOfMeasure, UDF1, UDF2, UDF3, UDF4, UDF5, AdditionalImageCount, PhotoName, AppendProductModifiers, Discontinued, 
                      IsDeleted
FROM         StagingProducts SG
WHERE
     (ManufacturerID = @ManufacturerID)

NOT EXISTS (SELECT * FROM
         Products P
       WHERE
          P.Key1 = SG.Key1 AND SG.Key2 = SG.Key2 AND SG.Key3 = SG.Key3)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...