views:

80

answers:

5

Let say I have a simple Stored Procedure:

ALTER PROCEDURE [dbo].[myProc]
AS
BEGIN
   SELECT * FROM myTable
END

How can I do a WHERE statement in Microsoft SQL Server Management Studio to the stored procedure? Something like that:

SELECT * FROM myProc WHERE x = 'a'; -- But that doesn't work...
+1  A: 

You can't add a WHERE clause to a stored procedure like this.

You should put the clause in the sproc, like this:

ALTER PROCEDURE [dbo].[myProc]
    @X VARCHAR(10)
AS
BEGIN
SELECT * FROM myTable WHERE x=@X
END
GO

The syntax for calling a stored procedure is through the use of EXECUTE not SELECT(e.g.):

EXECUTE dbo.myProc 'a'
AdaTheDev
I know but let say that I do not have the right to modify the procedure...
Daok
Then you'd have to execute the stored procedure into a temp table as Hythloth suggested and then run the restrictive query on that temp table. Though I really wouldn't use dynamic sql unless you really, really have to
AdaTheDev
+3  A: 

It sounds like you're trying to make a "dynamic" stored procedure.

Something you might want to do is:

1) Insert the contents of your stored procedure into a temporary table

2) Use dynamic sql to apply a where condition to that temporary table.

Something like:

declare @as_condition varchar(500); --Your condition

create table #a
(
id bigint
)

insert into #a
execute sproc

declare @ls_sql varchar(max);
set @ls_sql = "select * from #a where " + @as_condition;
execute (@ls_sql);
Hythloth
no need for dynamic SQLselect * from #a where x = 'a' Will work just fine.
HLGEM
Just make sure you define the temp table with exactly the same columns the stored proc returns in the same datatypes. It will not work unless the structures match.
HLGEM
+1  A: 

I think you can't do that.

First, the command to execute a stored procedure is EXECUTE. Here it is the reference of it:

http://msdn.microsoft.com/en-us/library/ms188332.aspx

See some more examples of the EXECUTE usage here:

http://www.sqlteam.com/article/stored-procedures-returning-data

rossoft
A: 

If you want the WHERE clause to be something you can "turn off" you can do this, passing in a predetermined value (e.g. -1) if the WHERE limitation is to be bypassed:

ALTER PROCEDURE [dbo].[myProc]    
@X VARCHAR(10)
AS

BEGIN
    SELECT * FROM myTable WHERE x=@X or @X = -1
END

GO
davek
+1  A: 

SQL Server allows you to use INSERT INTO to grab a stored procedure's output. For example, to grab all processes with SPID < 10, use:

create table #sp_who (
  spid   smallint,
  ecid   smallint,
  status    nchar(30),
  loginame  nchar(128),
  hostname  nchar(128),
  blk    char(5),
  dbname    nchar(128),
  cmd    nchar(16),
  request   int)

insert into #sp_who execute sp_who 

select * from #sp_who where spid < 10
Andomar