0

Say I have a table (lets call it Audit) in SQL Server

AuditID int primary not null,
Name varchar(300),
AuditCount int,
ActualCount int,
AuditDate datetime

The table could have any number of rows with a given AuditID in it. I want to iterate through the table, given an AuditID, and compare the AuditCount with the ActualCount. If they are not equal, then I'll do something else...but first, how do I retrieve one row at a time, and compare the values returned?

Amanda_Panda
  • 1,156
  • 4
  • 26
  • 68
  • You can iterate through one row at a time, but most people would use a set-based query to do this in SQL. See http://stackoverflow.com/questions/24168/why-are-relational-set-based-queries-better-than-cursors. – APH May 06 '16 at 22:34
  • 3
    You'll have to specify more concretely what *do something* might be: insert a record? delete a record? create a table? sum something? – trincot May 06 '16 at 22:34
  • is my answer helpful. If so mark it as answer – Jande Oct 05 '16 at 21:54

1 Answers1

1

Try this:

SELECT
    AuditID,
    Name,
    AuditCount,
    ActualCount,
    AuditDate
FROM Audit
WHERE AuditCount <> ActualCount; 

or

SELECT
        AuditID,
        Name,
        case when AuditCount <> ActualCount then 'Do something'
        else 'do something else' end as myColumn,
        AuditDate
FROM Audit;
Jande
  • 1,695
  • 2
  • 20
  • 32