[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 929
  • Last Modified:

sql cte rowcount

Hi I have a simple cte but I need to check to see if it returns any rows

Please see my code below. It seems that I can't put an "If" after the CTE. I get a syntax error

Thanks in advance
WITH Photos AS
(
SELECT ROW_NUMBER() OVER(Order by [CreatedDate] DESC) as RowNum 
      ,[id]        
      ,[CreatedDate]
      ,[ImageTitle]
      ,COUNT([id]) OVER () AS [totalRows]   
  FROM [dbo].[Photos]
  where   
    [UserId] = @Userid       
)

IF @@ROWCOUNT = 0 
BEGIN
    PRINT 'No Photos' 
    
END
ELSE
   PRINT 'Has photos'

Open in new window

0
doctor069
Asked:
doctor069
1 Solution
 
Ephraim WangoyaCommented:

Thats because you have not run any executable statement yet
Here
WITH Photos AS
(
SELECT ROW_NUMBER() OVER(Order by [CreatedDate] DESC) as RowNum 
      ,[id]        
      ,[CreatedDate]
      ,[ImageTitle]
      ,COUNT([id]) OVER () AS [totalRows]   
  FROM [dbo].[Photos]
  where   
    [UserId] = @Userid       
)

select * from Photos

IF @@ROWCOUNT = 0 
BEGIN
    PRINT 'No Photos' 
    
END
ELSE
   PRINT 'Has photos'

Open in new window

0
 
doctor069Author Commented:
Thanks - That is what I was missing!
0

Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now