-2

我在这里有一些代码,但首先我想解释我的问题。

我想创建一个视图,但这在视图中是不可能的,因为我的SELECT陈述variables中有一些我已经看到了一些答案,function但我不知道参数是如何工作的。

这是我的代码

代码:

DECLARE @totalRecords INT
DECLARE @I INT

SELECT @I = 1

SELECT @totalRecords = COUNT([Id]) FROM [dbo].[Werkzaamheden]

WHILE (@I <= @totalRecords)

BEGIN

SELECT 
    U.[Id]
    , G.[Naam]
    , W.[Omschrijving]
    , U.[datum]
    , CONVERT(VARCHAR,100)+'%' AS 'Status'
    , W.[Norm]
    , W.Id

FROM [Werkzaamheden] W
        RIGHT JOIN [Uitgevoerd] U ON U.[Taak] = W.[Id] /*or left */
        FULL JOIN [Gebruikers] G ON G.[Naam] = U.[Naam]

WHERE U.[Status]= 1 AND W.Id = @I

UNION 

SELECT 
    U.[Id]
    , G.[Naam]
    , W.[Omschrijving]
    , U.[datum]
    , CONVERT(VARCHAR,0)+'%' AS 'Status'
    , W.[Norm]
    , W.Id
FROM [Werkzaamheden] W
        LEFT JOIN [Uitgevoerd] U ON U.[Taak] = W.[Id] /*or left */
        FULL JOIN [Gebruikers] G ON G.[Naam] = U.[Naam]

WHERE U.[Status]= 0 AND W.Id = @I

UNION

SELECT 
    U.[Id]
    , G.[Naam]
    , W.[Omschrijving]
    , U.[datum]
    , null AS 'Status'
    , '' AS Norm
    , W.Id
FROM [Werkzaamheden] W
        RIGHT JOIN [Uitgevoerd] U ON U.[Taak] = W.[Id] /*or left */
        FULL JOIN [Gebruikers] G ON G.[Naam] = U.[Naam]

WHERE U.[Status]IS NULL 

    SELECT @I = @I + 1

END

什么是最好的问候?

这就是它返回的内容:

Id  Naam    Omschrijving    datum   Status  Norm    Id
NULL    Johan   NULL    NULL    NULL    0   NULL
8   Piet    Luisteren   2013-05-14  0%  95  3
9   Klaas   Luisteren   2013-05-16  100%    95  3
13  Klaas   Luisteren   2013-05-17  0%  95  3
14  Janneke Luisteren   2013-05-17  100%    95  3

Id  Naam    Omschrijving    datum   Status  Norm    Id
NULL    Johan   NULL    NULL    NULL    0   NULL
4   Janneke Schoonmaken 2013-05-14  100%    20  2
5   Jan Schoonmaken 2013-05-14  0%  20  2
10  Piet    Schoonmaken 2013-05-16  100%    20  2
11  Janneke Schoonmaken 2013-05-16  100%    20  2
12  Piet    Schoonmaken 2013-05-17  100%    20  2

那很好

4

1 回答 1

4

为什么不是这个?没有循环也没有UNION?

SELECT 
    U.[Id]
    , G.[Naam]
    , W.[Omschrijving]
    , U.[datum]
    , CASE
          WHEN U.Status = 1 THEN CONVERT(VARCHAR,100)+'%' 
          WHEN U.Status = 0 THEN CONVERT(VARCHAR,100)+'%' 
          ELSE NULL
      END AS 'Status'
    , W.[Norm]
    , W.Id

FROM [Werkzaamheden] W
        RIGHT JOIN [Uitgevoerd] U ON U.[Taak] = W.[Id] /*or left */
        FULL JOIN [Gebruikers] G ON G.[Naam] = U.[Naam]
WHERE
    U.Status = 0 OR U.Status = 1 OR U.Status IS NULL
于 2013-05-16T13:05:25.410 回答