Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with CTE 1

Status
Not open for further replies.

sparkbyte

Technical User
Sep 20, 2002
879
US
I am trying to write a CTE to control when an insert process runs.

I keep having problems with the IF statement.

Code:
WITH
	cteTotals (TTL_Prod, TTL_Dev)
AS
(
	Select 
		(Select Count(*) From MailroomTracking.dbo.tblTrackingTable),
		(Select Count(*) From MailroomTracking_DEV.dbo.tblTrackingTable)
)

--Select Sum(TTL_Prod-TTL_Dev) From cteTotals

--Select  
--	TTL_Prod, 
--	TTL_Dev,
--	Sum(TTL_Prod-TTL_Dev) As New_Rows
--From cteTotals
--Group by TTL_Prod, TTL_Dev

	If (Select Sum(TTL_Prod-TTL_Dev) From cteTotals) > 0 
		Begin 
			Print 'Perform Insert'
		End
	Else
		Print 'No new rows'

Thanks

John Fuhrman
 
Is there any reason to use CTE?
Why not:
Code:
DECLARE @TTL_Prod int
DECLARE @TTL_Dev  int
SET @TTL_Prod = 0
SET @TTL_Dev  = 0

Select @TTL_Prod = Count(*)
       From MailroomTracking.dbo.tblTrackingTable

Select @TTL_Dev  = Count(*)
       From MailroomTracking_DEV.dbo.tblTrackingTable

IF (@TTL_Prod - @TTL_Dev) > 0
   Begin
         Print 'Perform Insert'
   End
ELSE
   Begin
         Print 'Do NOT Perform Insert'
   End


Borislav Borissov
VFP9 SP2, SQL Server 2000,2005 & 2008.
 
Boris, to answer your question as to why. I thought it would be a fairly easy script to start with to see how CTE's work.

Your solution works. Which was very simular to my 1st solution. So why does the CTE version not work whith the same style If??

Code:
WITH
	cteTotals (TTL_Prod, TTL_Dev)
AS
(
	Select 
		(Select Count(*) From MailroomTracking.dbo.tblTrackingTable),
		(Select Count(*) From MailroomTracking_DEV.dbo.tblTrackingTable)
)

	If (TTL_Prod - TTL_Dev) > 0 
		Begin 
			Print 'Perform Insert'
		End
	Else
		Begin
			Print 'No new rows'
		End

Code:
[red]
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'If'.
[/red]


Thanks

John Fuhrman
 
In SQL Server you can not operate with the field's values in the procedural code.

In other words,

IF Field1 - Field2 > Some Value

is invalid syntax in SQL Server.

You can only operate with variables or constants using the IF logic.

In addition, CTE can only be used once after it created and it can only be used in the SET based statement.

PluralSight Learning Library
 
OK, I see now why that won't work as a CTE.

Thanks!!

Thanks

John Fuhrman
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top