存储过程的语法

时间:2014-07-09 06:02:25

标签: sql stored-procedures

我对存储过程很陌生,但是我的项目需要形成一个复杂的存储过程。

逻辑上,我有一些想法,但不知道存储过程的确切语法和规则..

  1. 我需要循环遍历表的不同属性
  2. distinct属性的每个值都会将另一个表的查询作为过滤条件
  3. 返回联盟表

    alter procedure dbo.someStoreProcedure
        @paramA varchar(255)
        ....
    
        declare @attributeA,@resultSql 
    
        while( (select count distinct attributeA from tableA where attributeB>@paramA and attributeB<@paramA+5)>0)//1.
    
        BEGIN
    
        @attributeA=select count distinct attributeA from tableA where         attributeB>@paramA and attributeB<@paramA+5
    
        @resultSql=
            select fieldA,fieldB,fieldC from tableB where fieldB=@attributeA//2,within         loop
        UNION 
            select attributeA,attributeB,attributeC from table A where attributeB=@attributeA//3
    
    
        END
    
  4. 返回每个循环的(3)和(2)的联合结果

1 个答案:

答案 0 :(得分:0)

目标DBMS是什么?如果postgresql,我想我可以重写你的示例代码,如

    CREATE OR REPLACE FUNCTION dbo.someStoreProcedure(VARCHAR, VARCHAR) RETURNS SETOF RECORD AS '
    DECLARE
        paramA ALIAS FOR $1;
        paramB ALIAS FOR $2;
        resultSql RECORD;
        attributeA BIGINT;
    BEGIN
        WHILE ((SELECT COUNT(DISTINCT attributeA) FROM tableA WHERE attributeB > paramA AND attributeB < paramA + 5) > 0)
        LOOP
            attributeA := (SELECT COUNT(DISTINCT attributeA) FROM tableA WHERE attributeB > paramA AND attributeB < paramA + 5);
            FOR resultSql IN
                SELECT fieldA, fieldB, fieldC FROM tableB WHERE fieldB = attributeA
                UNION
                SELECT attributeA, attributeB, attribute C FROM tableA WHERE attributeB = attributeA
            LOOP
                RETURN NEXT resultSql;
            END LOOP;
        END LOOP;
        RETURN;
    END
' LANGUAGE pgplsql;