SQL - 选择列,如果存在于OLEQuery中

时间:2017-04-07 10:27:35

标签: sql sql-server exists oledbconnection

在某些客户,我使用较旧的数据库,但现在我必须为新客户添加另一列。我的程序现在应该查询新列是否存在,如果不存在则使用NULL。

到目前为止,使用C#和OLEQuery:

string sql = @"SELECT i.[ID] AS cID, 
                        pg.[Name], 
                        pg.[ID] AS pgid, 
                        i.[time],
                        defect = CASE i.[defect] WHEN 0 THEN 'OK' WHEN 1 THEN 'NOK' END,                                           
                  FROM inspection AS i WITH (NOLOCK) INNER JOIN programs as pg ON i.programid = pg.[ID]
                  WHERE i.[time] BETWEEN ... ///SOME MORE CODE IS FOLLOWING HERE!
                    ";

但现在我想在此添加(可能/可能不是)现有列timeTo。

string sql = @"SELECT i.[ID] AS cID, 
                        pg.[Name], 
                        pg.[ID] AS pgid, 
                        i.[time],
                        defect = CASE i.[defect] WHEN 0 THEN 'OK' WHEN 1 THEN 'NOK' END,                      
                        timeTo = CASE i.[timeTo] WHEN EXISTS THEN i.[timeTo] ELSE NULL END                     
                  FROM inspection AS i WITH (NOLOCK) INNER JOIN programs as pg ON i.programid = pg.[ID]
                  WHERE i.[time] BETWEEN ... //SOME MORE CODE IS FOLLOWING HERE!
                    ";

我知道这个“exists”关键字很难,但有没有“一线”解决方案?我找到了几个其他案例选择解决方案由于我需要在具有不同列的几个地方使用此解决方案,因此案例选择解决方案不适合。 谢谢你的帮助

2 个答案:

答案 0 :(得分:1)

SQL Server不允许您引用不存在的字段。我怀疑这是因为查询优化器无法生成包含不存在的字段的执行计划。

您的应用需要:

  1. 确定正在使用的数据库版本。
  2. 选择适当的查询。
  3. 确保它处理丢失的数据(通过关闭依赖于新字段的功能或选择适当的默认值)。

答案 1 :(得分:0)

您可以执行if语句并查询系统表。你需要在动态sql中执行此操作才能进行解析。

declare @sql nvarchar(max);

if exists (
    select 1 from sys.columns c
    inner join sys.tables t on c.object_id = t.object_id
    where c.name = 'timeTo' and t.name = 'inspection')
begin
    set @sql = 'SELECT i.[ID] AS cID, 
        pg.[Name], 
        pg.[ID] AS pgid, 
        i.[time],
        defect = CASE i.[defect] WHEN 0 THEN ''OK'' WHEN 1 THEN ''NOK'' END,                      
        timeTo = CASE i.[timeTo] WHEN EXISTS THEN i.[timeTo] ELSE NULL END                     
    FROM inspection AS i WITH (NOLOCK) INNER JOIN programs as pg ON i.programid = pg.[ID]
    WHERE i.[time] BETWEEN ... //SOME MORE CODE IS FOLLOWING HERE!';
end
else 
begin
    set @sql = 'SELECT i.[ID] AS cID, 
        pg.[Name], 
        pg.[ID] AS pgid, 
        i.[time],
        defect = CASE i.[defect] WHEN 0 THEN ''OK'' WHEN 1 THEN ''NOK'' END,                                           
    FROM inspection AS i WITH (NOLOCK) INNER JOIN programs as pg ON i.programid = pg.[ID]
    WHERE i.[time] BETWEEN ... ///SOME MORE CODE IS FOLLOWING HERE!';
end
exec (@sql);