SQL Server – Inspecting Anonymous Column in Stored Procedure Resultset

sql serverstored-procedures

I am writing an SQL Script using a Stored Procedure, that somebody else wrote and I cannot change, which identifies whether or not a record can be safely deleted, based on its dependents.

My problem is that this stored procedure returns an anonymous resultset in the form of

IF <Condition>
BEGIN
  SELECT 'N', 'Cannot be deleted'
END
ELSE
BEGIN
  SELECT 'Y', ''
END

Now, I think this is poor design on the part of whoever wrote this because the messages are redundant, but that is besides the point because I cannot change it and so must work with what I have got.

The problem I have is that when I go to execute this proc

IF (EXEC CanDeleteRecord @RecordID = @Record_ID)

I don't really know how I am supposed to select the first column of the result set to compare with 'Y' or 'N' because the columns are anonymous. Is there some way of enumerating the results? This is a problem I have never encountered before with SQL and Google turns up squat.

Best Answer

Store the results in a temporary table or table variable and work with the stored set.

Here's a quick prototype you can work with.

create PROCEDURE [dbo].[TestMe]
AS
BEGIN
IF 1=1
BEGIN
  SELECT 'N', 'Cannot be deleted'
END
ELSE
BEGIN
  SELECT 'Y', ''
END
END


Declare @Results Table (CanDeleteIndicator char(1),Description varchar(30))
insert @Results exec dbo.testme
select * from @Results