在存储过程

时间:2017-05-03 12:53:18

标签: c# asp.net sql-server stored-procedures dynamic

我在修改模式下有一个如下的存储过程。我需要动态传递tablename甚至字符串连接也没关系。但由于对存储过程不太熟悉,我找不到这样做的方法。任何指导都会有所帮助。 testdata是表名。我需要动态传递@TableName。

 USE [test1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[TestDataTest]

@TicketId VARCHAR(12),
@TesterId int,
    @ValidatorId varchar(10),
@count int, 
   @TableName varchar(20),
@ReturnVal int output



AS
BEGIN
SET NOCOUNT ON;
DECLARE @ReserveStatus char(1),@ret int, @index int,@rs CHAR,@secindex INT,@value INT,@SQL nvarchar(500),@SQL1 nvarchar(500)
    BEGIN TRAN
    INSERT INTO TblStatus (TicketId,TesterId,ValidatorId)
    VALUES
   (@TicketId,@TesterId,@Validator)

    IF (@@ERROR<>0 )
      BEGIN
      ROLLBACK TRAN 
      SET @ReturnVal=2


      Return @ReturnVal
      END

    WHILE @count >0

       BEGIN

       SELECT  @index=CHARINDEX(' ', @TestDataIdstring,0)
       SELECT  @secindex=CHARINDEX(' ', @TestDataIdstring,(CHARINDEX(' ', @TestDataIdstring,0))+1)
       SELECT  @value=@secindex-@index
       SELECT @value
       select @SQL1 = N'Select ReserveStatus from ' + QUOTENAME(@TableName) + ' where TestDataId= rtrim(Ltrim(SUBSTRING(''' + @TestDataIdstring + ''',' + @index +',' + @value + ')))'
       execute sp_executesql @SQL1 , N'@RS int OUTPUT', @RS = @RS output;


       IF (@rs='N')
         BEGIN

     Set @SQL =  N'Update ' + QUOTENAME(@Tablename) + ' set  ReserveStatus=''Y'',TicketId=' + @TicketId + ' where TestDataId= rtrim(Ltrim(SUBSTRING(''' + @TestDataIdstring + ''',' + @index +',' + @value + ')))'
     Execute sp_executesql @SQL
         IF (@@ERROR<>0 )
            BEGIN
            ROLLBACK TRAN 
            SET @ReturnVal=2
            Return @ReturnVal
            END




COMMIT TRAN  

   SET @ReturnVal=3
   return @SQL
  return @returnval

  END   

1 个答案:

答案 0 :(得分:2)

您可以使用sp_ExecuteSQL命令。下面是一个将表名作为参数的简单示例。

Create Procedure dbo.DynamicSQL
(
    @Tablename nvarchar(50)
)
As

Declare @SQL nvarchar(500)

Set @SQL =   N'Select * from dbo.' + QUOTENAME(@Tablename)

EXECUTE sp_executesql @SQL

go

以下是我为您构建更新sql的尝试,然后通过sp_executesql执行它

声明@SQL nvarchar(500)

Set @SQL =  N'Update ' + QUOTENAME(@Tablename) + ' set  ReserveStatus=''Y'',TicketId=' + @TicketId + ' where TestDataId= rtrim(Ltrim(SUBSTRING(''' + @TestDataIdstring + ''',' + @index +',' + @value + ')))'
Execute sp_executesql @SQL

我认为传入的变量都是varchars!

要将值转换为@RS,这也是动态的,您需要添加它。

   select @SQL = N'Select ReserveStatus from ' + QUOTENAME(@TableName) + ' where TestDataId= rtrim(Ltrim(SUBSTRING(''' + @TestDataIdstring + ''',' + @index +',' + @value + ')))'
   execute sp_executesql @SQL , N'@RS char(1) OUTPUT', @RS = @RS output;