1. 程式人生 > 其它 >c# 呼叫 postgresql 儲存過程

c# 呼叫 postgresql 儲存過程

最近使用C#開發管理系統,其間使用儲存過程來更新資料,發現其特有的語法特點:SQL直接用儲存過程名

如:sql = "clientmatch";
clientmatch就是儲存過程名

因為在Navicat中的語法是:select clientmatch('yjlx','10736714',''),想當然的以為在C#中也是這樣,誰知老是報語法錯誤。

經過試錯,發現語句中的SQL直接寫儲存過程名(函式名)即可,其它的一律不用帶。(一定不能帶括號和引數,引數要另外宣告)

//使用儲存過程,更新下游客戶號
            sql = "clientmatch";
            NpgsqlParameter
[] sqlPara = new NpgsqlParameter[3]; //pgsql 的引數與SQL SERVER 的格式不一樣 sqlPara[0] = new NpgsqlParameter("@tmpfilename", NpgsqlTypes.NpgsqlDbType.Text, 30); sqlPara[0].Value = tmpTableName; sqlPara[1] = new NpgsqlParameter("@supplierid", NpgsqlTypes.NpgsqlDbType.Text
, 10); sqlPara[1].Value = supplierNumber; sqlPara[2] = new NpgsqlParameter("@clientname", NpgsqlTypes.NpgsqlDbType.Text, 100); sqlPara[2].Value = "";

       DBHelperPg.ExecuteStoreProcedure(sql, sqlPara);

附1:DBHelperPg.ExecuteStoreProcedure

public static int ExecuteStoreProcedure(string sql, params NpgsqlParameter[]
parameters) { int num2 = -1; using (NpgsqlConnection connection = new NpgsqlConnection(ConnectionString)) { using (NpgsqlCommand command = connection.CreateCommand()) { command.CommandText = sql; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddRange(parameters); try { connection.Open(); num2 = command.ExecuteNonQuery(); } catch (NpgsqlException exception) { //throw new Exception(exception.Message); MessageBox.Show(exception.Message + "\n 錯誤SQL:" + sql); } finally { connection.Close(); } } } return num2; }

呼叫的儲存過程

CREATE OR REPLACE FUNCTION "public"."clientmatch"("tmpfilename" text, "supplierid" text, "clientname" text)
  RETURNS "pg_catalog"."int4" AS $BODY$
declare 
    mysql  text ;
        mycolumn text ;
        filename text;
        supplier text;
        clientinfo text ;
        strwhere text; 

begin 
    --需要新建的欄位名
    filename = tmpfilename;
    supplier = supplierid
    clientinfo = clientname;
  mycolumn = '';
    ----------------------------------------------

    if supplier !='' then
        strwhere = ' and yjlx_gysbh ='||supplier|| ;
    end if;

    if clientinfo !='' then
        strwhere = strwhere || ' and yjlx_khmc ='''||clientinfo|| '''';
    end if;
    

    mysql = ' update "+ filename+" set yjlx_khbh =b.clientid from client_alias as b ';
    mysql = mysql || ' where yjlx_gysbh=b.supplierid and     yjlx_khmc=b.clientalias ';
    mysql = mysql ||strwhere;
            RAISE NOTICE 'SQL語句1為: %', mysql;
    
      execute mysql  ;

    mysql = ' update ' ||filename || ' set yjlx_khbh =b.id from client as b  where yjlx_khbh is null and yjlx_khmc=b.name ';
        mysql = mysql ||strwhere;
            RAISE NOTICE 'SQL語句2為: %', mysql;
      execute mysql  ;

  
    return 0;
end;

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
活到老,學到老。