SQL Server2008关于字符串截取的问题
现在有张tba表,表中a2列是字符串,如下表:
a1a2
1rb1207
2SB201207
3RTS201209
4p1212
说明:a2列中数值部分是日期,例如:rb1207表示2012年7月,RTS201209表示2012年9月。
现在将a2列中数值部分提取出来全部变成日期,然后查询成如下表:
a1a2
1201207
2201207
3201209
4201212
请问这个应该怎样实现?
基础数据源码:
USE tempdb;GOIF OBJECT_ID('tba') IS NOT NULL DROP TABLE tba;GOCREATE TABLE tba(a1 INT , a2 VARCHAR(20));INSERT INTO tba VALUES (1,'rb1207');INSERT INTO tba VALUES (2,'SB201207');INSERT INTO tba VALUES (3,'RTS201209');INSERT INTO tba VALUES (4,'p1212');
IF OBJECT_ID('tba') IS NOT NULL DROP TABLE tba;GOCREATE TABLE tba(a1 INT , a2 VARCHAR(20));INSERT INTO tba VALUES (1,'rb1207');INSERT INTO tba VALUES (2,'SB201207');INSERT INTO tba VALUES (3,'RTS201209');INSERT INTO tba VALUES (4,'p1212');IF OBJECT_ID('dbo.fn_get_number') IS NOT NULLDROP FUNCTION dbo.fn_get_numberGOCREATE FUNCTION dbo.fn_get_number(@S VARCHAR(100))RETURNS VARCHAR(100)ASBEGINWHILE PATINDEX('%[^0-9]%',@S) > 0BEGINset @s=stuff(@s,patindex('%[^0-9]%',@s),1,'')ENDRETURN @SENDselect right(dbo.get_number(a2),4)+200000 as new_a2 from tba /*new_a2201207201207201209201212*/
[解决办法]
IF OBJECT_ID('GET_NUMBER2') IS NOT NULLDROP FUNCTION DBO.GET_NUMBER2GOCREATE FUNCTION DBO.GET_NUMBER2(@S VARCHAR(100))RETURNS VARCHAR(100)ASBEGINWHILE PATINDEX('[^0-9]%',@S) > 0BEGINset @s=stuff(@s,patindex('%[^0-9]%',@s),1,'')ENDRETURN @SENDGO--测试select a1,case when len(cast(DBO.GET_NUMBER2("a2") as char(6)))=4 then '20'+cast(DBO.GET_NUMBER2("a2") as char(6)) else cast(DBO.GET_NUMBER2("a2") as char(6)) end aa from tbGO