子查询中的TSQL联盟

时间:2017-05-10 19:22:34

标签: sql sql-server sql-server-2008 tsql stored-procedures

我有一个名为Employee.emp.Language的表,其中包含可在UI上选择的语言列表。我无法在此表中添加记录,也无法直接编辑UI来解决我的问题。

我需要在查询中添加一个选项,将NULL添加到我的结果集中。这基本上允许用户从下拉列表中选择null

DECLARE @nulls AS TABLE (fieldLabel VARCHAR(10) NULL, fieldValue VARCHAR(10) 

NULL)
INSERT INTO @nulls( fieldLabel, fieldValue )
VALUES  ('NULL', NULL )

SELECT 
(
        SELECT  LanguageName AS FieldLabel,
                LanguageID AS FieldValue
        FROM    Employee.emp.Language
        WHERE  IsRetired = 0
        UNION
        SELECT fieldLabel ,
                fieldValue
            FROM @nulls
    FOR    XML PATH ('options'), ELEMENTS, TYPE, ROOT ('languages') 
)

虽然我的列表包含要在我的下拉列表中选择的null选项,但我无法将这段代码保存到我的存储过程中。

我得到的错误是:The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it.

我删除后跟unionselect一切正常。

我怎样才能在不将结果集直接添加到表中的情况下为结果集添加值?

2 个答案:

答案 0 :(得分:2)

将它用作子查询,并且您不需要表值,您可以使用带有空值的select。

create table lang(fieldlabel varchar(10), fieldvalue varchar(20));
insert into lang values 
('en', 'english'),
('fr', 'french');

select fieldlabel, fieldvalue
from (select fieldlabel, fieldvalue
      from   lang
      union all
      select null as fieldlabel, null as fieldvalue) l
FOR    XML PATH ('options'), ELEMENTS, TYPE, ROOT ('languages')
GO
| (No column name)                                                                                                                                                                              |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <languages><options><fieldlabel>en</fieldlabel><fieldvalue>english</fieldvalue></options><options><fieldlabel>fr</fieldlabel><fieldvalue>french</fieldvalue></options><options /></languages> |

dbfiddle here

答案 1 :(得分:0)

尝试直接插入空值而不是使用单独的表。尝试:

Sub Delete089()
    Dim LastRow As Long, n As Long
    LastRow = Range(H2000000).End(xlUp).Row
    For n = LastRow To 1 Step -1
        If Cells(n, 2).Value <= 0.089 Then Cells(n, 2).EntireRow.Delete
    Next n
End Sub

Sub Delete089()

Dim i As Long

    With Application

        .Calculation = xlCalculationManual

        .ScreenUpdating = False

    For i = Selection.Rows.Count To 1 Step -1

        If WorksheetFunction.CountA(Selection.Rows(i)) < 0.89 Then

            Selection.Rows(i).EntireRow.Delete

        End If

    Next i

        .Calculation = xlCalculationAutomatic

        .ScreenUpdating = True

    End With

End Sub

来自How to use union all with manual value (not from another tabel)?

注意:编辑回答