我有一个表,该表有一个列,我在其中存储逗号分隔的文本,每个逗号分隔的值都用单引号引起来。这些值是员工ID。这是它的外观
现在,我有一个SQL查询,其中需要将该列的值放入SQL IN运算符。像这样的东西:
select *
from EMPLOYEE_MASTER
where EMPLOYEEID IN (select CM_CONFIG_VALUE
from ADL_CONFIG_MAST_T
where CM_CONFIG_KEY like 'ATT_BIOMETRIC_OU_ID'
)
但是,这行不通,查询执行时返回0行,而如果我像下面这样正常执行查询,则行得通。
select *
from EMPLOYEE_MASTER
where EMPLOYEEID IN('9F3DD4B791554DDE','C9B90D62851D43AB','828CB9E6204B4DDC')
请提出我应该在这里做什么。我已经尝试过使用子字符串来删除第一个和最后一个字符,并假设单引号可能是问题所在,但这也不起作用。
select * from EMPLOYEE_MASTER where EMPLOYEEID IN(select EMPLOYEEID from ADL_CONFIG_MAST_T where CM_CONFIG_KEY like 'ATT_BIOMETRIC_OU_ID')
列的位置应与COLUMNNAME IN的位置相同(从表名中选择COLUMNNMAE)
您可以创建一个临时变量,然后使用exec
命令获得所需的结果。
declare @temp varchar(200)
select @temp=CM_CONFIG_VALUE
from ADL_CONFIG_MAST_T
where CM_CONFIG_KEY like 'ATT_BIOMETRIC_OU_ID'
exec('select *
from EMPLOYEE_MASTER
where EMPLOYEEID IN (' + @temp + ')')
尝试此:
DECLARE @ID VARCHAR(500);
DECLARE @Number VARCHAR(500);
DECLARE @comma CHAR;
SET @comma = ','
SET @ID = 'select CM_CONFIG_VALUE
from ADL_CONFIG_MAST_T
where CM_CONFIG_KEY like ''%ATT_BIOMETRIC_OU_ID% ''' + @comma;
Create table #temp (EMPLOYEEID varchar(500))
WHILE CHARINDEX(@comma, @ID) > 0
BEGIN
SET @Number = SUBSTRING(@ID, 0, CHARINDEX(@comma, @ID))
SET @ID = SUBSTRING(@ID, CHARINDEX(@comma, @ID) + 1, LEN(@ID))
Insert into #temp
select @Number
END
select *
from EMPLOYEE_MASTER
where EMPLOYEEID IN(select EMPLOYEEID from #temp)