|
-
May 29th, 2007, 09:08 AM
#1
Thread Starter
PowerPoster
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.
-
May 29th, 2007, 10:02 AM
#2
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.
-
May 29th, 2007, 10:56 AM
#3
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
-
May 29th, 2007, 12:49 PM
#4
Thread Starter
PowerPoster
Re: SELECT FROM parameter as viewName?
yes I mean SQL Server, sorry shouldve cleared that up initially
thanks
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|