通用sql批处理执行过程

一个通用的执行sql的过程,用于接收参数,找到数据库里的存储的SQL语句,并拼接参数并执行的过程,能解决普通项目中绝大部分的业务,留存备用

CREATE PROC [dbo].[MY_EXEC_SQL]
@Code   NVARCHAR(100),
@Param  NVARCHAR(MAX)
AS
BEGIN
    DECLARE @id   INT;
    DECLARE @cnt  INT;
    DECLARE @str  NVARCHAR(MAX);
    DECLARE @key  NVARCHAR(100);
    DECLARE @val  NVARCHAR(MAX);
    DECLARE @sql  NVARCHAR(MAX);
    DECLARE @params  TABLE(
        id INT,
        content NVARCHAR(MAX)
    );
    DECLARE @keyVal  TABLE(
        id INT,
        content NVARCHAR(MAX)
    );
    SELECT @sql = SqlStr FROM MySqlTable WHERE Code = @Code;
    INSERT INTO   @params SELECT * FROM MY_SPLIT(@Param, '§');
    SET    @key = '';
    SET    @val = '';
    SET    @id  = 1;
    SELECT @cnt = COUNT(1) FROM @params;
    WHILE  @id <= @cnt
    BEGIN
        SELECT @str = Content FROM @params WHERE id = @id;
        INSERT INTO   @keyVal SELECT * FROM MY_SPLIT(@str, '|');
        SELECT @key = Content FROM @keyVal WHERE id = 1;
        SELECT @val = Content FROM @keyVal WHERE id = 2;
        SET    @sql = REPLACE(@sql, @key, @val);
        SET    @id  = @id + 1;
        SET    @key = '';
        SET    @val = '';
        DELETE @keyVal;
    END
    EXEC(@sql);
END

 

你可能感兴趣的:(数据库应用)