比较并更新字符串中的两个字符

时间:2016-09-09 09:26:40

标签: sql sql-server sql-server-2008

我有一个名为keyguardManager.isKeyguardSecure()的表格,其中包含:

if (keyguardManager.isKeyguardSecure())
        {
            Toast.makeText(context, "Screen unlocked", Toast.LENGTH_LONG).show();
        }

enter image description here

我想比较点(a)的左字符和点(b)的右字符,如果a = b,则删除table1

因此col1 a.b 1.1 2.2 3.3 1.3 2.3 必须更改为:

.b

enter image description here

2 个答案:

答案 0 :(得分:2)

试试这个:

DECLARE @tbl1 as TABLE(
   Id  INT,
   col1  VARCHAR(20)
)

INSERT INTO @tbl1 VALUES(1,'1.1')
INSERT INTO @tbl1 VALUES(2,'2.2')
INSERT INTO @tbl1 VALUES(3,'3.3')
INSERT INTO @tbl1 VALUES(4,'1.3')
INSERT INTO @tbl1 VALUES(5,'1.4')

SELECT
    Id,
    CASE WHEN SUBSTRING(col1,0,CHARINDEX('.',col1))=SUBSTRING(col1,CHARINDEX('.',col1)+1,len(col1))
    THEN SUBSTRING(col1,0,CHARINDEX('.',col1))
    ELSE col1
    END
FROM
@tbl1

<强>更新

UPDATE @tbl1 
    SET col1=SUBSTRING(col1,0,CHARINDEX('.',col1))
WHERE SUBSTRING(col1,0,CHARINDEX('.',col1))=SUBSTRING(col1,CHARINDEX('.',col1)+1,len(col1))

答案 1 :(得分:0)

我会将update写为:

with toupdate as (
      select t1.*,
             left(t1.col1, charindex('.', t1.col1 + '.') - 1) as firstpart
      from table1 t1
     )
update toupdate
     set col1 = firstpart
     where col1 = firstpart + '.' + firstpart;