Results 1 to 4 of 4

Thread: SELECT FROM parameter as viewName?

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    SELECT FROM parameter as viewName?

    in SQL when using say a SPROC (Stored Procedure), is there a way to use a parameter for the "FROM" part of the statement?

    for example:


    SELECT @fieldName FROM @viewOrTableName


    ?

    if so how? as currently the syntax error is that @viewOrTableName must be declared, but they are as parameters....in addition what about the fieldname parameter?
    Last edited by Techno; May 29th, 2007 at 09:15 AM.

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: SELECT FROM parameter as viewName?

    Do you mean SQL Server?

    If so, you can't do that unfortunately.. you need to create a string in the SP, and put the SQL statement into it - then you can run it using (I think) Exec.

  3. #3
    Fanatic Member kaffenils's Avatar
    Join Date
    Apr 2004
    Location
    Norway
    Posts
    946

    Re: SELECT FROM parameter as viewName?

    If there is a limited number of view names you could use IF...ELSE to check the value in the variable, and write separate SELECT statements for each value.

    On the other hand, if the name of the views are unknown, the only solution I can think of is building dynamic SQL. Keep in mind that you should check for SQL injections when using the dynamic sql option. E.g. use the QUOTENAME() function and check that the variables doesn't contain -- or /*.
    Add the SELECT statement to a variable and execute it with the sp_executesql stored procedure.

    Code:
    declare @sql nvarchar(4000)
    
    set @sql=N'SELECT '+QUOTENAME(@fieldName)+N' FROM '+QUOTENAME(@viewOrTableName)
    
    exec sp_executesql @sql

  4. #4

    Thread Starter
    PowerPoster
    Join Date
    Aug 2003
    Location
    Edinburgh, UK
    Posts
    2,773

    Re: SELECT FROM parameter as viewName?

    yes I mean SQL Server, sorry shouldve cleared that up initially

    thanks

    MVP 2007-2010 any chance of a regain?
    Professional Software Developer and Infrastructure Engineer.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width