如何在PostgreSQL中的函数内传递变量

时间:2016-12-23 16:53:03

标签: postgresql function plpgsql

我正在从bat文件(Windows 7)运行 km_test.sql

call psql -h ... -U ... -d ... -f C:\svn\tre2\prog\km_test.sql -v nrl=%a%

其中%a%是整数。我正在运行PostgreSQL 9.5。

km_test.sql 看起来像这样

\set n :nrl

DROP FUNCTION km_test(integer);
CREATE FUNCTION km_test(n integer)
  RETURNS void AS
$BODY$
DECLARE
   j smallint;

BEGIN
   DROP TABLE IF EXISTS km_test CASCADE;
   CREATE UNLOGGED TABLE km_test (
     lnr smallint,
     km_id character varying(16),
     flatenr smallint,
     geo geometry(Linestring,25833)
    );
  j = 1;
  WHILE j < n+1 LOOP
    RAISE NOTICE 'Verdi j er : %', j;
    INSERT INTO km_test (lnr, km_id, flatenr, geo)
      SELECT d.i,
             p.km_id,
             CAST(substring(p.flatenr from 5 for 4) AS smallint),
             ST_MakeLine(p.geo,(ST_Translate(p.geo, d.dx, d.dy)))
      FROM org_tre2.km_punkter_des2016 AS p, org_tre2.km_dxdy1 AS d
      WHERE j = d.i;
    j = j + 1;
  END LOOP;
  COMMENT ON TABLE org_tre2.km_test IS 'KM innsyn: n innsynslinjer for kulturminnepunkt utenfor IK i tre2-flater';
END;
$BODY$
LANGUAGE plpgsql;

\set tab 'org_tre2.km_punkter_des2016'
select km_test(:n);

问题:如何将表p(org_tre2.km_punkter_des2016)作为输入参数?这意味着如何在函数调用中包含tablename(使用select km_tull(:n,:p))并在函数中引用该表?

CREATE FUNCTION km_test(n integer, t text)
...

select km_test(:n,:'tab')

到目前为止,我还没有设法将input-table称为FROM语句中的t变量。 可能吗?或者有解决方法吗?

1 个答案:

答案 0 :(得分:1)

感谢提示/链接@McNets。我想我已经明白了。更正 km_test.sql

中的代码
    public class Test
    {
        public Date2 startDate;

        public List<Test> testList = new List<Test>();

        public struct Date2
        {
            public static explicit operator Date2(DateTime date)
            {
                return default(Date2);
            }

            public static explicit operator DateTime(Date2 date)
            {
                return default(DateTime);
            }
        }


        public DateTime BS()
        {
            var tmp = testList.LastOrDefault();
            var testDate = ((DateTime?)tmp?.startDate) ?? DateTime.MaxValue;
            return testDate;
        }
    }

var test = new Test();
test.BS();
var x = test.BS();

正在使用EXECUTE的解决方案,将所有INSER INTO代码放在''中,将s声明为变量并在WHERE子句中使用s代替j。