Question : If EXISTS with a Union statement - SQL Server 2005

Hello Experts,

I am trying to Use IF logic to either UPDATE a table (If the records already exist) or INSERT records into the table (If the records don't alrready exist). I am trying to do this from an UPDATE or INSERT of View UNIONS.

The UPDATE, INSERT and UNIONS work fine but I can't seem to get the IF EXEISTS and ELSE to work.

see code snippet...

Does anyone know how to do this??

Thanks!
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
--If Exists Union views and update the table
IF EXISTS(UPDATE Table_1
SET ColDate = X.ColDate, ColB = X.ColB, ColC = X.ColC FROM
SELECT ColDate, ColB, SUM(ColC) AS ColC
GROUP BY  ColDate, ColB FROM View_1
UNION ALL
SELECT ColDate, ColB, SUM(ColC) AS ColC
GROUP BY  ColDate, ColB FROM View_2
)X
 
ELSE--Union  views and insert into the table
INSERT INTO Table_1(ColDate, ColB, ColC)
SELECT ColDate, ColB, ColC FROM
(
SELECT ColDate, ColB, SUM(ColC) AS ColC
GROUP BY  ColDate, ColB FROM View_1
UNION ALL
SELECT ColDate, ColB, SUM(ColC) AS ColC
GROUP BY  ColDate, ColB FROM View_2
)X
WHERE ColDate = '1/25/2008'
ORDER BY ColDate, ColB, ColC
Open in New Window Select All

Answer : If EXISTS with a Union statement - SQL Server 2005

try this
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
--If Exists Union views and update the table
IF EXISTS(SELECT ColDate FROM Table_1 WHERE ColDate = '1/25/2008')
BEGIN
 
	UPDATE Table_1
		SET ColDate = X.ColDate, ColB = X.ColB, ColC = X.ColC 
	FROM
	(
		SELECT ColDate, ColB, SUM(ColC) AS ColC
		FROM View_1
		WHERE ColDate = '1/25/2008' 
		GROUP BY  ColDate, ColB 
		UNION ALL
		SELECT ColDate, ColB, SUM(ColC) AS ColC
		FROM View_2
		WHERE ColDate = '1/25/2008' 
		GROUP BY  ColDate, ColB 
	) X
	
 
END
 
ELSE
BEGIN
 
	INSERT Table_1(ColDate, ColB, ColC)
	SELECT ColDate, ColB, SUM(ColC) AS ColC
	FROM View_1
	WHERE ColDate = '1/25/2008' 
	GROUP BY  ColDate, ColB 
	UNION ALL
	SELECT ColDate, ColB, SUM(ColC) AS ColC
	FROM View_2
	WHERE ColDate = '1/25/2008' 
	GROUP BY  ColDate, ColB 
	
END
Open in New Window Select All
Random Solutions  
 
programming4us programming4us