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

时间:2013-11-29 07:50:52

标签: sql-server tsql stored-procedures

我想将表名作为参数传递,我希望在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 个答案:

答案 0 :(得分:3)

未经测试,但您需要使用Dynamic 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

答案 1 :(得分: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