Solved

sql cte rowcount

Posted on 2011-03-16
2
893 Views
Last Modified: 2012-06-27
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
Comment
Question by:doctor069
2 Comments
 
LVL 32

Accepted Solution

by:
ewangoya earned 500 total points
Comment Utility

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
 

Author Closing Comment

by:doctor069
Comment Utility
Thanks - That is what I was missing!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now