查找表中的列并提取值(如果存在)则引用其他列

时间:2017-08-22 14:18:29

标签: sql sql-server-2008

我试图检查表[EMPLOYEE]中的列[EMPID]如果存在,我必须考虑该列中的值,如果不是,则必须引用另一个TAble [Details]和[EMPID]列。请有人能回答这个问题。

select distinct EMPLYEENAME,(
select case 
   when exists (select 1 from sys.columns where Name = 'EMPID' and 
   object_id=object_id('EMPLOYEE'))
   then 1
   else 0 
end EMPID) EMPID from EMPLOYEE
)k

所以这里代替'1'和'0'我必须从DETAILS表和EMPLOYEE表中提取值

2 个答案:

答案 0 :(得分:0)

可能最好做这样的事情。在执行查询之前首先检查列,这样您就不会错过列错误:

IF EXISTS(select 1 from sys.columns where Name = 'EMPID' and object_id=object_id('EMPLOYEE'))
    select distinct EMPLYEENAME, EMPID from EMPLOYEE
ELSE
    select distinct EMPLYEENAME, 0 AS EMPID from EMPLOYEE

答案 1 :(得分:0)

这将检查列名是否在表上,如果没有,这将从另一个表中选择

IF EXISTS(SELECT 1 FROM sys.columns WHERE name = 'EMPID' AND object_id=object_id('EMPLOYEE'))
    SELECT DISTINCT employeename,
           empid
      FROM employee
ELSE
    SELECT columns -- list your column names here
      FROM details