如何简化此SQL代码?

时间:2017-04-28 05:14:29

标签: sql sql-server

需要协助简化以下代码。我的目标是找到带有前缀的产品,并在数据库中与客户核对。如果找到更多客户,请将null或空白。如果它只是一个记录,请放置公司名称。

是否有任何可能的方法而不是使用光标这是另一种方法,例如CTE,子查询

DECLARE 
     @PartNumber VARCHAR(MAX) -- PartNumber
     ,@PartNumberPrefix VARCHAR(MAX)
     ,@ProductName VARCHAR(MAX)
     ,@Count INT
     ,@CompanyName VARCHAR(MAX)

DECLARE @Temp TABLE (PartNumberPreFix VARCHAR(MAX),
                     RealPartNUmber VARCHAR(MAX),
                     CompanyName VARCHAR(MAX)
                    )

DECLARE db_cursor CURSOR FOR  
    SELECT 
        PART_NUMBER, PRODUCT_NAME,
        (CASE CHARINDEX(' ', PART_NUMBER, 1)  WHEN 0 THEN PART_NUMBER -- empty or single word
    ELSE SUBSTRING(PART_NUMBER, 1, CHARINDEX(' ', PART_NUMBER, 1) - 1) --  multi-word
         END)
    FROM PRODUCT 
    WHERE IS_ACTIVE = 1 
      AND PRODUCT_TYPE_ID = 1 
      AND IS_SELLABLE = 1
      --AND id IN(49,50)

OPEN db_cursor   

FETCH NEXT FROM db_cursor INTO @PartNumber, @ProductName, @PartNumberPrefix   

WHILE @@FETCH_STATUS = 0   
BEGIN   
     SELECT @PartNumberPrefix = (CASE CHARINDEX(' ', @PartNumber, 1)
     WHEN 0 THEN @PartNumber -- empty or single word
     ELSE SUBSTRING(@PartNumber, 1, CHARINDEX(' ', @PartNumber, 1) - 1) -- multi-word
     END)   

     SELECT @Count = COUNT(*) FROM COMPANY WHERE COMPANY_NAME LIKE ('%' + LTRIM(RTRIM(@PartNumberPrefix)) + '%') AND TYPE_Id = 2

     SELECT @CompanyName = COMPANY_NAME FROM COMPANY WHERE COMPANY_NAME LIKE ('%' + LTRIM(RTRIM(@PartNumberPrefix)) + '%') AND TYPE_Id = 2

     --SELECT 'Before---------'+ @PartNumberPrefix, @CompanyName,    @Count

     IF @Count > 1 OR @CompanyName IS NULL OR @Count = 0
     SET @CompanyName = ''

     --SELECT 'After------------'+ @PartNumberPrefix, @CompanyName

     -- Insert into Temp Table   
     INSERT INTO @Temp (PartNumberPreFix,CompanyName,RealPartNUmber)
     VALUES (@PartNumberPrefix,@CompanyName,@PartNumber) 


     FETCH NEXT FROM db_cursor INTO @PartNumber,@ProductName,@PartNumberPrefix   
END   

CLOSE db_cursor   
DEALLOCATE db_cursor

SELECT * FROM @Temp

1 个答案:

答案 0 :(得分:0)

我认为您可以使用单个查询来执行此操作,如下所示(此外,在我看来,不使用列productname)。你可以尝试一下让我知道吗?

{{1}}