3

What is the best way to do the equivalent of execute scalar in T-SQL? In other words, using SQL, how can I get the first column of the first row of the first result set when I call a stored procedure?

Edit: Just to clarify, this is only using SQL, no client-side language. The result set could be something like:

Id Description
--------------
1  foo
2  bar

I only want "1" in a variable.

The only way I know how to do this is with a temp table (untested, but you get the idea):

INSERT #TempTable EXEC MyStoredProcedure

DECLARE @id INT;

SELECT TOP(1) @id = Id FROM #TempTable
Nelson Rothermel
  • 9,436
  • 8
  • 62
  • 81

3 Answers3

1

Your temp table solution is probably the only option.

SQL isn't really designed for this

gbn
  • 422,506
  • 82
  • 585
  • 676
0

if you're talking about .net client, then you can use SQLCommand.ExecuteScalar.

if not please add an example of how this would look exactly for your case.

EDIT: you can do this since you provided extra info:

-- add 'loopback' linkedserver 
if exists (select * from master..sysservers where srvname = 'loopback')
 exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver @server = N'loopback',
 @srvproduct = N'',
 @provider = N'SQLOLEDB', 
 @datasrc = @@servername
go

select top 1 * @id = id 
from openquery(loopback, 'exec MyStoredProcedure') 
go

However this is far from ideal, plus you have to enable ad hoc queries for this to work

Mladen Prajdic
  • 15,457
  • 2
  • 43
  • 51
0

This is the only way I can think of, from what you're asking. =)

select TOP 1 nameOfFirstColumnReturnedBySP as Column1 from dbo.MyStoredProcedure

EDIT #1

-- Assuming this temporary table represents the data structure returned by the SP.
CREATE TABLE @Data (
    Column1 int
    , Column2 nvarchar(10)
)

insert into @Data
    exec dbo.MyStoredProcudure

select TOP 1 Column1
    from @Data

Related link: Stored Procedures: Returning Data

I hope this helps! =)

Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162