带有Table变量的LIKE语句

时间:2015-05-12 01:06:13

标签: sql-server

我想使用表变量中的值来执行SELECT语句。

declare @emailids   TABLE (usrmst_id INT)
declare @actionids  TABLE (tskmst_id INT)

insert into @emailids (usrmst_id)
    select usrmst_id 
    from usrmst 
    where usrmst_domain = 'EMAIL'

insert into @actionids (tskmst_id)
    select tm.tskmst_id 
    from tskmst tm
    inner join tskmail tml 
        on tml.tskmail_id = tm.tskmst_id
    where 
        tskmail_to_int like '%' + (select cast(usrmst_id as CHAR(5)) from @emailids) + '%'

select * from @actionids

这显然是失败的,因为select cast(usrmst_id as CHAR(5)) from @emailids有多个结果。我想要做的是为@emailids表中的每个值生成一个返回@actionids表。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用INNER JOIN代替:

insert into @actionids (tskmst_id)
    select tm.tskmst_id 
    from tskmst tm
    inner join tskmail tml 
        on tml.tskmail_id = tm.tskmst_id
    inner join @emailids e
        on tskmail_to_int like '%' + cast(e.usrmst_id as varchar(5)) + '%'

您应该CASTVARCHAR而不是CHAR。我相信转换为CHAR用空格填充字符串直到达到定义的长度。因此,当您CAST 60到CHAR(5)时,它会变为60[space][space][space]