将SQL Server语句传递到存储过程,以便存储过程可以执行它们

时间:2017-04-11 06:20:39

标签: sql-server tsql dynamic-sql

我有以下SQL Server存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Create date: April 4 2017
-- Description: This stored procedure deletes a selected row from the table.
-- =============================================
ALTER PROCEDURE [dbo].[StoredProcedureTestbench_Delete]
    @TestKey INT = NULL
AS
BEGIN
    SET NOCOUNT ON;  -- NOCOUNT 

    -- This always deletes the last record from the table.
    DELETE FROM StoredProcedureTest
    WHERE TestKey = (SELECT MAX(TestKey) FROM StoredProcedureTest)     
END;
RETURN

我使用:

执行它
/*  This routine executes the stored procedure that deletes a selected StoredProcedureTestbench table row  */
SET QUOTED_IDENTIFIER ON
GO

DECLARE @ReturnCode int;

EXECUTE @ReturnCode = dbo.StoredProcedureTestbench_Delete
BEGIN
    SELECT @ReturnCode AS Return_Code
END;
GO

是否可以将'(SELECT MAX(TestKey) FROM StoredProcedureTest)'从调用存储过程作为参数的过程传递给存储过程?

从更一般的意义上讲,如何将SQL Server语句传递给存储过程,以便存储过程可以执行它们?

1 个答案:

答案 0 :(得分:0)

我会告诉你如何做到这一点,但请阅读所有评论说你不应该认真使用它,并想一想你正在做的事情是肯定安全的。

SQL注入意味着您应该100%确定用户不会为“drop database”这样的文本更改sql参数,从所有表中选择所有数据等等。

如果您自己控制该参数,就像您创建该字符串而您确定它是安全的,您可以这样做:

sp_executesql将执行您动态创建的sql。

ALTER PROCEDURE [dbo].[StoredProcedureTestbench_Delete] @sqltextparameter varchar(max),
    @TestKey INT = NULL
AS
BEGIN
    SET NOCOUNT ON;   

 declare @executestatement varchar(max)
    set @executestatement = 'DELETE FROM StoredProcedureTest
    WHERE TestKey ='

   exec  sp_executesql @executestatement + @sqltextparameter 
END;
RETURN

以后再执行它将您的文本添加为​​参数:

/*  This routine executes the stored procedure that deletes a selected StoredProcedureTestbench table row  */
SET QUOTED_IDENTIFIER ON
GO

DECLARE @ReturnCode int;

EXECUTE @ReturnCode = dbo.StoredProcedureTestbench_Delete '(SELECT MAX(TestKey) FROM StoredProcedureTest)'
BEGIN
    SELECT @ReturnCode AS Return_Code
END;
GO