如何从Select语句[Sql Query]中分离空值和空值以获得结果

时间:2016-05-23 07:39:42

标签: sql sql-server sql-server-2008 sql-server-2012

这是我的XML字符串

'<DocumentElement>
  <XMLExport>
    <VehicleNo>TR45TA1234</VehicleNo>          --- > VEHICLE PRESENT IN DB [ALLOW]
  </XMLExport>
  <XMLExport>
    <VehicleNo/>                               ---> VEHICLE NO IS EMPTY [Allow]
  </XMLExport>
  <XMLExport>
    <VehicleNo>TR45TA123412121</VehicleNo>     ---> VEHICLE NOT IN DB  [DO NOT ALLOW]
  </XMLExport>
</DocumentElement>'

我正在将Excel文件读入Datatable,然后读取XML String。我需要像

这样的结果
1st Part : If Vehicle No. present in **DB** Then **Allow** To Upload
2nd Part : If Vehicle No. Column is EMPTY Then **Allow** 
3rd Part : If Vehicle No is not Empty and Not present in **DB** Then DO NOT Allow 

这是我的查询

create table #UplaodXMLDemo
(
 VehicleNo varchar(20),
) 

INSERT INTO #UplaodXMLDemo
SELECT 
ExportPass.EP.value('VehicleNo[1]', 'VARCHAR(15)')as VehicleNo,
FROM  @XMLString.nodes('/DocumentElement/XMLExport')ExportPass(EP)  


  SELECT  VehicleNo,VH_SRNO,
  (
   select Top 1 case when ltrim(rtrim(ISNULL(CDX_MST_VEHICLE.VH_NUMBER,'')))  is not null then 'YES' else 'NO' End As IsVehicleExist   from CDX_MST_VEHICLE where CDX_MST_VEHICLE.VH_NUMBER =UD.VehicleNo
 ) as IsVehicleExist

FROM #UplaodXMLDemo UD 
left join CDX_MST_VEHICLE ON CDX_MST_VEHICLE.VH_NUMBER =UD.VehicleNo

怎么做,我得到了上面的结果。

1 个答案:

答案 0 :(得分:0)

只需将空<table cellpadding=0 cellspacing=0 height=50 width=50 style="font-size:0px;height:50;width:50"> <tr> <td> <table cellpadding=0 cellspacing=0 height=50 width=50 style="font-size:0px;height:50px;width:50px"> <tr height=0> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> <td width=1 /> </table 添加到您VehicleNo

的表格中即可
Left Join

也可能值得考虑NULL Declare @XMLString xml = '<DocumentElement> <XMLExport> <VehicleNo>TR45TA1234</VehicleNo> </XMLExport> <XMLExport> <VehicleNo/> </XMLExport> <XMLExport> <VehicleNo>TR45TA123412121</VehicleNo> </XMLExport> <XMLExport> </XMLExport> </DocumentElement>'; With UplaodXMLDemo As ( SELECT ExportPass.EP.value('VehicleNo[1]', 'VARCHAR(15)') as VehicleNo FROM @XMLString.nodes('/DocumentElement/XMLExport')ExportPass(EP) ), CDX_MST_VEHICLE As ( SELECT 'TR45TA1234' As VH_NUMBER ) Select UplaodXMLDemo.* , CASE WHEN Allowed.VehicleNo IS NULL THEN 'NO' ELSE 'YES' END AS Decision From UplaodXMLDemo Left Join ( Select VH_NUMBER As VehicleNo From CDX_MST_VEHICLE Union Select '' --< Add empty value to allow it too ) Allowed On Allowed.VehicleNo = COALESCE(UplaodXMLDemo.VehicleNo, '') 测试用例。