日期:2014-05-18  浏览次数:20666 次

SQL Server2008关于字符串截取的问题
现在有张tba表,表中a2列是字符串,如下表:
a1 a2
1 rb1207
2 SB201207
3 RTS201209
4 p1212
说明:a2列中数值部分是日期,例如:rb1207表示2012年7月,RTS201209表示2012年9月。
现在将a2列中数值部分提取出来全部变成日期,然后查询成如下表:
a1 a2
1 201207
2 201207
3 201209
4 201212
请问这个应该怎样实现?
基础数据源码:
SQL code

USE tempdb;
GO
IF OBJECT_ID('tba') IS NOT NULL 
DROP TABLE tba;
GO
CREATE 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');



------解决方案--------------------
SQL code

IF OBJECT_ID('tba') IS NOT NULL 
DROP TABLE tba;
GO
CREATE 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 NULL
DROP FUNCTION dbo.fn_get_number
GO
CREATE FUNCTION dbo.fn_get_number(@S VARCHAR(100))
RETURNS VARCHAR(100)
AS
BEGIN
WHILE PATINDEX('%[^0-9]%',@S) > 0
BEGIN
set @s=stuff(@s,patindex('%[^0-9]%',@s),1,'')
END
RETURN @S
END

select right(dbo.get_number(a2),4)+200000 as new_a2 from tba 
/*
new_a2
201207
201207
201209
201212
*/

------解决方案--------------------
SQL code

IF OBJECT_ID('GET_NUMBER2') IS NOT NULL
DROP FUNCTION DBO.GET_NUMBER2
GO
CREATE FUNCTION DBO.GET_NUMBER2(@S VARCHAR(100))
RETURNS VARCHAR(100)
AS
BEGIN
WHILE PATINDEX('[^0-9]%',@S) > 0
BEGIN
set @s=stuff(@s,patindex('%[^0-9]%',@s),1,'')
END
RETURN @S
END
GO
--测试
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 tb
GO