Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Passing fieldnames as parameter in stored procedure

Posted on 2016-10-04
4
Medium Priority
?
81 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 35

Assisted Solution

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


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

sp_executesql @sql
0
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 1000 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 35

Assisted Solution

by:ste5an
ste5an earned 600 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have a large data set and a SSIS package. How can I load this file in multi threading?
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

604 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