2016-06-08 68 views
0

我慢慢地學習了關於PostgreSQL的更多信息,因爲我們試圖從MSSQL Server遷移到它。postgresql執行動態sql命令

在MSSQL中,我有以下代碼:

DECLARE ServiceabilityParameters 
CURSOR FORWARD_ONLY READ_ONLY STATIC LOCAL FOR 
SELECT WorkbookParameterType.ID, 
     WorkbookParameterType.Name, 
     WorkbookParameter.DefaultValue, 
     WorkbookParameter.CommandText 
FROM WorkbookParameter 
JOIN WorkbookParameterType ON WorkbookParameterType.ID = WorkbookParameter.WorkbookParameterTypeID 
JOIN WorkbookParameterDirectionType ON WorkbookParameterDirectionType.ID = WorkbookParameter.WorkbookParameterDirectionTypeID 
AND          WorkbookParameterDirectionType.Writable = 1 
WHERE WorkbookParameter.WorkbookID = @WorkbookID 

OPEN ServiceabilityParameters 

FETCH NEXT FROM ServiceabilityParameters INTO @WorkbookParameterTypeID, @WorkbookParameterTypeName, @WorkbookDefaultValue, @WorkbookCommandText 

WHILE @@FETCH_STATUS = 0 
BEGIN 
DECLARE @ActualValue  NVARCHAR(256) = NULL  

IF @WorkbookCommandText IS NOT NULL 
BEGIN 
    EXEC sp_executesql @statement    = @WorkbookCommandText, 
         @params     = N'@ApplicationContainerID INT, @Value NVARCHAR(256) OUTPUT', 
         @ApplicationContainerID = @ApplicationContainerID, 
         @Value     = @ActualValue OUTPUT 
END 

IF @ActualValue IS NULL AND @WorkbookDefaultValue IS NOT NULL 
BEGIN 
    SET @ActualValue = @WorkbookDefaultValue 
END 

INSERT @InputParameters (
    ID, Name, Value 
) VALUES (
    @WorkbookParameterTypeID, @WorkbookParameterTypeName, @ActualValue 
) 

FETCH NEXT FROM ServiceabilityParameters INTO @WorkbookParameterTypeID, @WorkbookParameterTypeName, @WorkbookDefaultValue, @WorkbookCommandText 
END 

CLOSE ServiceabilityParameters 
DEALLOCATE ServiceabilityParameters 

我試圖找出如何做一個PostgreSQL功能sp_executesql的一部分。我相信我可以完成剩下的工作,但是我發現的大多數示例都顯示了一個簡單的選擇,可能有一些變量,而我需要使用參數執行另一個函數,其中函數名稱是表格中的文本。

很多謝謝。

+1

https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN –

回答

0

我想你想要做的是EXECUTE 'some string',就像this

EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2' 
    INTO c 
    USING checked_user, checked_date; 

另一種選擇是創建和使用自己的PL/PGSQL functions

+0

不是真的......除非'一些字符串'可以是另一個函數的名稱與參數...但無論如何歡呼。 – Boothy

+0

你有沒有試過,@布斯? – hdiogenes