sql:我的数据重复了一遍

时间:2013-12-04 12:49:22

标签: sql sql-server

BUG

当我执行我的代码时,它可以工作,但我的数据会重复。打印只是为了看看它是什么。

DECLARE @Variable1 NVARCHAR(MAX)
DECLARE @Variable2 NVARCHAR(MAX) 
DECLARE @Variable3 NVARCHAR(MAX)

CREATE TABLE #Temp1 (MAI_ID BIGINT, FUN_ID BIGINT)
CREATE TABLE #tmp2 (MAI_ID BIGINT, Variable1 NVARCHAR(MAX),Variable2 NVARCHAR(MAX), Variable3 NVARCHAR(MAX))

INSERT INTO #Temp1
SELECT TOP 10 ISD_MainID, ISNULL(ISD_FUNID,0)
FROM [dev_SAB_EM].[dbo].[SiteDetails]
ORDER BY ISD_ID DESC

DECLARE @MAI_ID BIGINT 
DECLARE @FUN_ID BIGINT

 WHILE (SELECT COUNT(MAI_ID) FROM #Temp1) <> 0
 BEGIN
SELECT TOP 1 @MAI_ID = MAI_ID, @FUN_ID = FUN_ID FROM #Temp1
PRINT @MAI_ID
PRINT @FUN_ID
SELECT @Variable1 = ISNULL(FUN_Name,'') FROM [dev_SAB_Man].[dbo].[fx_GetFUNStructureCTE_Asc] (@FUN_ID) WHERE FUN_Level = 1
SELECT @Variable2 = ISNULL(FUN_Name,'') FROM [dev_SAB_Man].[dbo].[fx_GetFUNStructureCTE_Asc] (@FUN_ID) WHERE FUN_Level = 2
SELECT @Variable3 = ISNULL(FUN_Name,'') FROM [dev_SAB_Man].[dbo].[fx_GetFUNStructureCTE_Asc] (@FUN_ID) WHERE FUN_Level = 3

INSERT INTO #tmp2(MAI_ID, Variable1, Variable2, Variable3) 
SELECT @MAI_ID, @Variable1, @Variable2, @Variable3 

DELETE FROM #Temp1 WHERE MAI_ID = @MAI_ID AND FUN_ID = @FUN_ID
  END

  SELECT * FROM #tmp2

DROP TABLE #Temp1
DROP TABLE #tmp2

fx_GetFUNStructureCTE_Asc

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fx_GetFUNStructureCTE_Asc] (@param_FUNID int)
RETURNS @FUN_Names table 
(
    [Level_Label] nvarchar(255),
    [FUN_Name] nvarchar(255),
    [FUN_Level] int, 
    [FUN_ID] int
)
AS
BEGIN
with cte([Level_Label],[FUN_Name],[FUN_Level],[FUN_ID],[FUN_FUNID]) as
(
    select ful1.FUL_Name,fu1.FUN_Name,fu1.FUN_Level,fu1.FUN_ID,fu1.FUN_FUNID
    from FunctionalUnits fu1
    inner join FunctionalUnitLevels ful1 on ful1.FUL_Level=fu1.FUN_Level
    where fu1.FUN_ID=@param_FUNID
    union all
    select ful2.FUL_Name,fu2.FUN_Name,fu2.FUN_Level,fu2.FUN_ID,fu2.FUN_FUNID
    from FunctionalUnits fu2
    inner join FunctionalUnitLevels ful2 on ful2.FUL_Level=fu2.FUN_Level
    inner join CTE a on a.FUN_FUNID=fu2.FUN_ID
)

    insert into @FUN_Names
    ([Level_Label],[FUN_Name],[FUN_Level],[FUN_ID])
    (select [Level_Label],[FUN_Name],[FUN_Level],[FUN_ID] from cte 
        where exists (select FUA_isActive from FunctionalUnitsActive where FUA_isActive=1))

return
RETURN
END

GO

任何建议或任何可以解雇我的事情? 好的,我添加了fx_GetFUNStructureCTE_Asc

1 个答案:

答案 0 :(得分:0)

考虑到您提供的信息,除了@Lamak所说的内容之外,它还可能取决于ISD_FUNID表上的字段[dev_SAB_EM].[dbo].[SiteDetails]值。如果它们在每条记录上都相同,那么您的代码就没有问题......

但是,这是一个基本假设......

并且,假设您在评论中所说的ISD_FUNID的值为NULL,可能会发生以下情况:当字段的所有值FUN_ID时在表0上是#Temp1当您对函数[dev_SAB_Man].[dbo].[fx_GetFUNStructureCTE_Asc]执行查询时会发生的是,所有行都将在赋值发生时循环,将变量值设置为返回的最后一个功能。

它会使所有#tmp2行的所有变量值都相同。您可能需要改进函数调用以仅返回一个值。