比较两列(一个varchar,一个int)

时间:2013-09-06 15:18:36

标签: sql-server

我正在构建一个临时表是sqlserver。现在在这个临时表中,我想检查另一列的文本字段中是否存在一个列整数值。

对于前。我有col。具有2,10,15,30 ...的值的日期,并且对于每个值多次,以及具有对规则集的描述的整个文本的另一列,并且最后,时间线为2日历天或30个日历天或10个工作日,应与整数列匹配。

如何比较规则文本列中文本匹配中的int值?

对于前。

col1   col2
2      ....should happen....- 2 business days
4      ....should happen....- 4 business days
5      ....should happen....- 5 business days
6      ....should happen....- 6 business days
15     ....should happen....- 15 business days
30     ....should happen....- 30 business days

3 个答案:

答案 0 :(得分:2)

您可以从字符串中过滤掉int,如下所示。 (基于一些假设:only one '-' in the string before the number, number has left and right spaces

declare @s varchar(100) = '...should happen....- 20 business days'

;with cte as (
    select right(@s,len(@s)-charindex('-',@s,0)- 1) as rightText
)
select left(rightText, charindex(' ', rightText,0))
from cte

查询就像

;with cte as (
    select col1, col2,
           right(col2,len(col2)-charindex('-',col2,0)- 1) as rightText

    from yourTable
 )
 select col1,col2
 from cte
 where left(rightText, charindex(' ', rightText,0)) = col1

答案 1 :(得分:1)

SELECT *
FROM TEMP
WHERE col2 LIKE '%- '+cast(col1 as varchar)+' % days'

请参阅SQLFIDDLE

或者可能是:

SELECT *,
       CASE WHEN col2 LIKE '%- '+cast(col1 as varchar)+' % days' 
            THEN 'Exists' 
            ELSE 'Not Exists' END AS "Exists"
FROM TEMP

请参阅SQLFIDDLE

对于msi77:

<强> Results

| COL1 |                                    COL2 |     EXISTS |
|------|-----------------------------------------|------------|
|    2 |  ....should happen....- 2 calendar days |     Exists |
|    2 | ....should happen....- 20 calendar days | Not Exists |
|    4 |  ....should happen....- 4 calendar days |     Exists |
|    5 |  ....should happen....- 5 business days |     Exists |
|    6 |  ....should happen....- 6 business days |     Exists |
|   15 | ....should happen....- 15 business days |     Exists |
|  999 | ....should happen....- 00 business days | Not Exists |
|   30 | ....should happen....- 30 business days |     Exists |

答案 2 :(得分:0)

首先,您可以从varchar中获取数字:

SUBSTRING(col2, CHARINDEX('-', col2) + 1, 2)

然后你可以把它转换成这样的INT:

CONVERT(INT, SUBSTRING(col2, CHARINDEX('-') + 1, 2))

SUBSTRING

CHARINDEX

CONVERT