Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 93
  • Last Modified:

Passing fieldnames as parameter in stored procedure

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
mcrmg
Asked:
mcrmg
3 Solutions
 
NorieData ProcessorCommented:
Try something like this.


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

sp_executesql @sql
0
 
Éric MoreauSenior .Net ConsultantCommented:
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
 
ste5anSenior DeveloperCommented:
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
 
mcrmgAuthor Commented:
thank you
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now