日期:2014-05-18 浏览次数:20610 次
tab1 a1 a2 a3 1 23 2 63 3 43 4 53 5 66 6 67
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba') BEGIN DROP TABLE tba END GO CREATE TABLE tba ( a1 INT, a2 INT, a3 INT ) GO INSERT INTO tba SELECT 1,23,0 UNION SELECT 2,63,0 UNION SELECT 3,43,0 UNION SELECT 4,53,0 UNION SELECT 5,66,0 UNION SELECT 6,67,0 GO UPDATE tba SET a3 = CASE WHEN CHARINDEX('3',LTRIM(a2)) > 0 THEN 1 ELSE 0 END + CASE WHEN CHARINDEX('6',LTRIM(a2)) > 0 THEN 1 ELSE 0 END SELECT * FROM tba a1 a2 a3 1 23 1 2 63 2 3 43 1 4 53 1 5 66 1 6 67 1
------解决方案--------------------
USE tempdb; GO IF OBJECT_ID('testtb') IS NOT NULL DROP TABLE testtb; GO CREATE TABLE testtb (a1 INT IDENTITY(1,1), a2 INT NULL , a3 INT NULL ); GO INSERT INTO testtb VALUES(23,NULL); INSERT INTO testtb VALUES(63,NULL); INSERT INTO testtb VALUES(43,NULL); INSERT INTO testtb VALUES(53,NULL); INSERT INTO testtb VALUES(66,NULL); INSERT INTO testtb VALUES(67,NULL); GO UPDATE dbo.testtb SET a3=(CASE WHEN PATINDEX('%3%',CAST(a2 AS CHAR(4)))<>0 THEN 1 ELSE 0 END)+ (CASE WHEN PATINDEX('%6%',CAST (a2 AS CHAR(4)))<>0 THEN 1 ELSE 0 END ); SELECT * FROM dbo.testtb; /*--结果 a1 a2 a3 1 23 1 2 63 2 3 43 1 4 53 1 5 66 1 6 67 1 */