Solved

Passing fieldnames as parameter in stored procedure

Posted on 2016-10-04
4
40 Views
Last Modified: 2016-10-04
Hi,

I have a sp like this
 
ALTER PROCEDURE [dbo].[st_test] @SelectString as varchar(8000)

as
select
@SelectString

from t1
ORDER BY userid

Open in new window


When I exec this sp
exec [st_test] "some string"

It does not return the value I need, instead, it returns number of rows in the table with "some string" as values.  Any ideas?  thanks
0
Comment
Question by:mcrmg
4 Comments
 
LVL 33

Assisted Solution

by:Norie
Norie earned 100 total points
ID: 41828608
Try something like this.


SET @sql = 'SELECT ' + @SelectString + ' FROM t1 ORDER BY userid'

sp_executesql @sql
0
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 250 total points
ID: 41828612
you need to use dynamic SQL to be able to do that. have a look at http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure
0
 
LVL 32

Assisted Solution

by:ste5an
ste5an earned 150 total points
ID: 41828613
First of all: Such a generic procedure is not useful under most circumstances..

The only way to do it, is by using dynamic SQL, which has it's problems (scope, permissions, execution plans):

ALTER PROCEDURE [dbo].[st_test]
    @Columns AS NVARCHAR(MAX)
AS
    DECLARE @SQL NVARCHAR(MAX) = N'
        SELECT @SelectString
        FROM t1;'
    SET @SQL = REPLACE(@SQL, '@Columns', @Columns)
    EXECUTE (@SQL);

Open in new window


Read also Erland's excellent article: The Curse and Blessings of Dynamic SQL
0
 

Author Closing Comment

by:mcrmg
ID: 41828621
thank you
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now