Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i want to pass a select query in a stored procedure as an argumnet

Tags:

sql

sql-server

I made this procedure..

ALTER PROCEDURE [dbo].[MyProcedure]
            @pSelect nvarchar
AS
BEGIN
    SET NOCOUNT ON;

    select @pSelect from tabel1
END

I want to pass a select query like from c# code to this stored procedure

MyProcedure("column1,column2");

How could I do this because stored procedure treat my parameter as a string and it behaves like

select N'column1,column2' from tabel1

pls help me

or provide a better option for this

like image 231
Amit Bisht Avatar asked Aug 28 '13 05:08

Amit Bisht


People also ask

Can we use SELECT statement in stored procedure?

We can not directly use stored procedures in a SELECT statement.

How do I pass a stored procedure parameter in SQL?

There are two ways to pass parameters to a stored procedure using SQLExec. One way, which works across all versions of Visual FoxPro, is to build the SQL command as a string variable. The advantage of this method is that you can check the string and see exactly which SQL command you are passing to the back end.

How do you pass dynamic parameters in SQL query?

The best way to pass the dynamic values to a SQL query is by using parameters. In order to use this option, click on "Edit query" in "Execute Query" or "Execute nonquery" activity. Click on the Parameters property in the Input section and pass the parameters.

How do I create a parameterized SQL query?

Declare statements start with the keyword DECLARE , followed by the name of the parameter (starting with a question mark) followed by the type of the parameter and an optional default value. The default value must be a literal value, either STRING , NUMERIC , BOOLEAN , DATE , or TIME .


1 Answers

You'll have to use dynamic sql inside the stored procedure.

ALTER PROCEDURE [dbo].[MyProcedure]
    @pSelect nvarchar(max)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @SQL nvarchar(max)

    SET @SQL = 'select ' + @pSelect + ' from tabel1';

    EXEC (@SQL)
END

Here's a script to test the above stored procedure:

CREATE TABLE tabel1 (id int, data varchar(50))
INSERT INTO tabel1 VALUES(1,'aaa'),(2,'bbb'),(3,'ccc')

EXEC [dbo].[MyProcedure] 'id'
EXEC [dbo].[MyProcedure] 'data'
EXEC [dbo].[MyProcedure] 'id,data'
like image 134
TheQ Avatar answered Sep 27 '22 20:09

TheQ