在Postgres中返回一个包含N列的空表

时间:2018-01-14 02:37:49

标签: postgresql function common-table-expression

我有一个Postgres函数,即RETURNS TABLE。我想在CTE零行的情况下返回一个空表。像

这样的东西
SELECT (CASE WHEN (SELECT count(1) FROM mycte = 0) 
        THEN (SELECT ... ??) -- not sure what to put here to return zero rows
        ELSE (SELECT ...)    -- A normal database query
        END) 

我怎样才能做到这一点?只写SELECT没有别的东西会返回一列。 SELECT x, y FROM ()不起作用。 SELECT (SELECT , SELECT)无效。

2 个答案:

答案 0 :(得分:0)

如果通过"空表"你的意思是没有行,然后就不要返回任何东西。

在PL / pgSQL函数中,不做任何事情(或执行单个RETURN;)。

在SQL函数中,将WHERE falseLIMIT 0添加到SELECT,以便不返回任何行。像:

SELECT -- your "ELSE" stuff here
WHERE EXISTS (SELECT 1 FROM mycte);

(计数会比EXISTS更贵。

答案 1 :(得分:0)

尝试一下:

Sub test()
    Dim Ws As Worksheet, newWs As Worksheet, Temp As Worksheet
    Dim vDB, vSp, vR()
    Dim i As Long, r As Long, n As Long, k As Integer, cnt As Integer
    Dim PN_01 As Range


    Set newWs = Sheets("New Sheet")
    Set oldWs = Sheets("OLD SHEET")
    Set Temp = Sheets.Add
    oldWs.Range("a54:d57").SpecialCells(xlCellTypeVisible).Copy Temp.Range("a1")
    vSp = Temp.UsedRange
    Application.DisplayAlerts = False
    Temp.Delete
    Application.DisplayAlerts = True
    With newWs
        vDB = .Range("a1", "d" & .Range("a" & Rows.Count).End(xlUp).Row)
        Set PN_01 = .Range("M17")
    End With
    cnt = UBound(vSp, 1)
    r = UBound(vDB, 1)

    For i = 1 To r
        n = n + 1
        ReDim Preserve vR(1 To 4, 1 To n)
        For j = 1 To 4
            vR(j, n) = vDB(i, j)
        Next j
        If vDB(i, 3) = PN_01 Then
            For k = 1 To cnt
                n = n + 1
                ReDim Preserve vR(1 To 4, 1 To n)
                For j = 1 To 4
                    vR(j, n) = vSp(k, j)
                Next j
            Next k
        End If
    Next i
    newWs.Range("a1").Resize(n, 4) = WorksheetFunction.Transpose(vR)
    newWs.Activate
End Sub

http://www.sqlfiddle.com/#!17/61913/15