SQL查询 - IF和ELSE

时间:2013-08-30 19:38:56

标签: sql sql-server-2005

我有一个表dbo.VBAK,其中包含VKORG, VBELN and SPART

如何正确编写以下查询

If dbo.tblVBAK.VKORG = '1001' 
BEGIN
   select dbo.tblVBAK.VKORG as 'Sales Org Approved' from dbo.tblVBAK
END
ELSE
BEGIN
   Select dbo.tblVBAK.VKORG as 'Sales Org Not Approved' from dbo.tblVBAK
END

我正在使用SQL Server 2005

3 个答案:

答案 0 :(得分:2)

SELECT CASE 
       WHEN VKORG = '1001' 
       THEN 'Sales Org Approved' 
       ELSE 'Sales Org NOT Approved' 
       END,
       VBELN,
       SPART
FROM   dbo.tblVBAK

如果您想将它们放在不同的列上,那么:

SELECT CASE 
       WHEN VKORG = '1001' 
       THEN VKORG
       END AS 'Sales Org Approved',
       CASE 
       WHEN VKORG <> '1001' 
       THEN VKORG
       END AS 'Sales Org Not Approved',
       VBELN,
       SPART
FROM   dbo.tblVBAK

答案 1 :(得分:0)

我相信你想要这个:

SELECT 
 CASE WHEN VKORG = '1001' THEN VKORG ELSE NULL END as 'Sales Org Approved',
 CASE WHEN VKORG != '1001' THEN VKORG ELSE NULL END as 'Sales Org Not Approved'
FROM tblVBAL

答案 2 :(得分:0)

可以使用UNION

完成另一种方法
SELECT VKORG AS 'Sales Org Approved', 
       null AS 'Sales Org Not Approved', 
       VBELN,
       SPART
FROM tblVBAK
WHERE VKORG = '1001'
UNION ALL
SELECT null AS 'Sales Org Approved', 
       VKORG AS 'Sales Org Not Approved', 
       VBELN,
       SPART
FROM tblVBAK
WHERE VKORG != '1001';