在动态t-sql中传递参数的问题

时间:2011-05-25 06:45:28

标签: sql sql-server tsql dynamic-sql

在此存储过程中传递参数时我做错了什么?:

ALTER PROCEDURE [dbo].[Unload]
    @branch_id INT,
    @fl_close BIT
AS
BEGIN
    SET NOCOUNT ON;
    IF object_ID('TempDb..##ttable','U') IS NOT NULL
        DROP TABLE ##ttable;

    DECLARE @ExecStr varchar(4000),
            @paramlist varchar(4000);
    SElECT @ExecStr = 'CREATE TABLE #ttables
    (
         numid INT identity(1,1),
         uso_id INT
    )     

    INSERT INTO #ttables (uso_id)
    SELECT u2.uso_id FROM Uso u2 WHERE u2.branch_id = @branch_id;'

    SElECT @ExecStr = @ExecStr + 'SELECT identity(int,1,1) as id, c.client_code,
          a.account_num, u.uso_id
    INTO ##ttable
    FROM accounts a INNER JOIN Clients c ON 
          c.id = a.client_id INNER JOIN Uso u ON c.uso_id = u.uso_id INNER JOIN 
          Magazin m ON a.account_id = m.accoun t_id INNER JOIN #ttables tt 
          ON u.uso_id = tt.uso_id 
    WHERE m.status_id IN (1,5) AND a.fl_close = @fl_close AND 
          u.branch_id = @branch_id';

    SElECT @ExecStr = @ExecStr + ';  
            SELECT  id,
                client_code,
                abs_account_num,
                account_new_num,
                account_new_open_date,
                account_close_date,
                uso_id
            FROM ##ttable;
            DROP TABLE #ttables;
            DROP TABLE ##ttable;'

   SELECT @paramlist = N'@branch_id INT, @fl_close BIT';
   EXEC sp_executesql @ExecStr, @paramlist, @branch_id, @fl_close;

1 个答案:

答案 0 :(得分:3)

参数值传递正常。

CREATE PROCEDURE [dbo].[Unload]
    @branch_id INT,
    @fl_close BIT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ExecStr NVARCHAR(4000),
            @paramlist NVARCHAR(4000);
    SELECT @ExecStr = 'select @branch_id, @fl_close'

   SELECT @paramlist = N'@branch_id INT, @fl_close BIT';

   EXEC sp_executesql @ExecStr, @paramlist, @branch_id, @fl_close

   END

  GO

  EXEC [dbo].[Unload] 20,1

返回

----------- -----
20          1