Go Premium for a chance to win a PS4. Enter to Win

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

Sql Server - input parameter for query

Hi,

   I have a simple requirement .

     I need to run a query on sql server studio

     How can I use an input variable to declare the Tablename I query

        I was looking something like  select  * from  @MyTable
       But looks like this is not possible (Sql Injection?) , Is there any alternative?
0
Sam OZ
Asked:
Sam OZ
2 Solutions
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Here you go, but the obvious question is why do you want to do this?
CREATE PROC your_proc (@table_name varchar(100)) AS

Declare @sql varchar(1000) 
SELECT @sql = 'SELECT * FROM ' + @table_name

exec sp_executesql @sql
GO

Open in new window

0
 
LowfatspreadCommented:
you could do it like that but its not advisable...

could you elaborate on why you think select * from "tobeadvisedtable" is a simple requirement....

and why you want to use studio to do it?

realistically how many tables and what sizes are you wanting to access (and what do you intend to do with the results)
0
 
Scott PletcherSenior DBACommented:
If you're gonna do this, you might as well add more flexibility into it, such as optionally allowing db name and/or schema name to be specified, as well as a row count (to generate a "TOP (nnn)" expression if needed).


DECLARE @MyTable varchar(1000)
DECLARE @exec_sql bit
DECLARE @rowcount int
DECLARE @column_list varchar(5000)

SET @MyTable = 'table_name'
--SET @MyTable = 'db_name.schema_name.table_name'
SET @exec_sql = 1
--SET @rowcount = 10
--SET @column_list = 'id, customerNumber'

------------------------------------------------------------------------------------------------------------------------

DECLARE @sql varchar(8000)

SET @sql = 'SELECT ' +
    CASE WHEN @rowcount > 0 THEN 'TOP (' + CAST(@rowcount AS varchar(10)) + ') ' ELSE '' END +
    ISNULL(@column_list, '*') +
    ' FROM ' +
    ISNULL('[' + PARSENAME(@MyTable, 3) + '].', '') +
    ISNULL('[' + PARSENAME(@MyTable, 2) + '].', CASE WHEN PARSENAME(@MyTable, 3) IS NULL THEN '' ELSE '.' END) +
    '[' + PARSENAME(@MyTable, 1) + ']'

PRINT @sql
IF @exec_sql > 0
    EXEC(@sql)
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

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