3

I am creating a query that will select all data on the table. The query will select to the table base on the variable that I will pass on the stored procedure.

Here in my example. If I execute example_sp table1 it will select in table1. Same thing if I use example_table table2, it should selecttable2.

ALTER PROCEDURE example_sp
    @type varchar(10), -- value will be `table1` or `table2`
AS
BEGIN
    SELECT * FROM @type
END
1
  • 1
    If you are going to pass in a table name like this you should use the sysname datatype instead of varchar(10). And follow the example that Gordon posted below making sure you use QUOTENAME as he did in his fine example. That will greatly help reduce the risk of sql injection. Commented Dec 20, 2016 at 20:47

3 Answers 3

5

A slightly different version of what Gordon has suggested.....

ALTER PROCEDURE example_sp
    @TableName SYSNAME   --<-- Use appropriate data type for sql server objects
AS
BEGIN
  SET NOCOUNT ON;

  Declare @Sql NVARCHAR(MAX);

  SET @Sql = N' SELECT * FROM ' + QUOTENAME(@TableName)

  Exec sp_executesql @Sql
END
Sign up to request clarification or add additional context in comments.

Comments

4

You need dynamic SQL to pass in identifiers such as table names and column names:

ALTER PROCEDURE example_sp (
    @tablename varchar(10) -- value will be `table1` or `table2`
)
AS
BEGIN
    DECLARE @sql NVARCHAR(MAX);

    SET @sql = 'SELECT t.* FROM @tablename t';

    SET @sql = REPLACE(@sql, '@tablename', QUOTENAME(@tablename));

    EXEC sp_executesql @sql;
END;

6 Comments

Why not do the table name in a single statement instead of two?
Just curious... why the replace and not a simple concat ?
execute example_sp(''';DROP TABLE STUDENTS;')
@Stavr00 the QUOTENAME greatly minimizes the risk of sql injection here. Plus your example won't fit in the varchar(10) either. :)
@Stavr00 "Little Bobby Tables" approves this message!
|
0

Your SP will have to return 2 result sets, one being empty. Just put both SELECT statements, including WHERE @type = 'table1'

It's even better if the result sets match, in which case you can simply merge them with UNION

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.