将表名作为参数传递给sql server

时间:2021-12-16 10:26:41

I want to pass table name as parameter and I want to that parameter in where clause

我想传递表名作为参数,我想在where子句中的那个参数

CREATE PROC [dbo].[bb_GetPrepositionInfo] 
    @userid INT,@propId INT,@tabName varchar(50)
AS 
      SET NOCOUNT ON 
      SET XACT_ABORT ON  

     BEGIN TRAN 

    SELECT *
    FROM   @tblname
    WHERE  ([acq_id] = @propId AND [user_id] = @userid) 

   COMMIT
    GO

2 个解决方案

#1


3  

Not tested but You need to use Dynamic SQL.

未经测试但您需要使用动态SQL。

CREATE PROC [dbo].[bb_GetPrepositionInfo] 
    @userid INT,@propId INT,@tabName varchar(50)
AS 
    SET NOCOUNT ON 
    SET XACT_ABORT ON  

    BEGIN TRAN

    DECLARE @SQL varchar(250)
    SELECT @SQL = 'SELECT * FROM ' + QuoteName(@tabName) + ' where acq_id=' + Quotename(@propId) + ' AND user_id=' + Quotename(@userid)
    EXEC (@SQL)

    COMMIT
GO

#2


2  

CREATE PROC [dbo].[bb_GetPrepositionInfo] 
  DECLARE  @userid INT
  DECLARE   @propId INT 
  DECLARE  @tabName varchar(50)
  DECLARE @sqlCommand varchar(200)
AS 
  SET NOCOUNT ON 
  SET XACT_ABORT ON  

  BEGIN TRAN

  SET @sqlCommand = 'SELECT * from ' + @tabName +'WHERE  [acq_id]='+  @propId +'AND   [user_id] = '+ @userid 
  EXEC (@sqlCommand)

  COMMIT
 GO

#1


3  

Not tested but You need to use Dynamic SQL.

未经测试但您需要使用动态SQL。

CREATE PROC [dbo].[bb_GetPrepositionInfo] 
    @userid INT,@propId INT,@tabName varchar(50)
AS 
    SET NOCOUNT ON 
    SET XACT_ABORT ON  

    BEGIN TRAN

    DECLARE @SQL varchar(250)
    SELECT @SQL = 'SELECT * FROM ' + QuoteName(@tabName) + ' where acq_id=' + Quotename(@propId) + ' AND user_id=' + Quotename(@userid)
    EXEC (@SQL)

    COMMIT
GO

#2


2  

CREATE PROC [dbo].[bb_GetPrepositionInfo] 
  DECLARE  @userid INT
  DECLARE   @propId INT 
  DECLARE  @tabName varchar(50)
  DECLARE @sqlCommand varchar(200)
AS 
  SET NOCOUNT ON 
  SET XACT_ABORT ON  

  BEGIN TRAN

  SET @sqlCommand = 'SELECT * from ' + @tabName +'WHERE  [acq_id]='+  @propId +'AND   [user_id] = '+ @userid 
  EXEC (@sqlCommand)

  COMMIT
 GO