sql server中的子串? [英] substring in sql server ?
本文介绍了sql server中的子串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
hi
如何使用子串选择此NVARCHAR
4-1-2015
5-1- 2015
1个月
4天和5天
2015年我的
hi
how can i use substring to select this NVARCHAR
4-1-2015
5-1-2015
1 is the month
4 and 5 days
2015 my year
推荐答案
使用substring是一种脏的方法。问题是当你的日子和月份变成两位数时;然后你必须写一堆条件来获得正确的字符,或者另外使用CHARINDEX来获取/的位置,然后用它后面的字符做一些事情。
我的建议是将CAST用作DateTime。请参阅下面的示例:
Using substring is the dirty way to do this. The problem is when your days and months become two digits; then you'd have to write a bunch of conditions to get the correct character or additionally use CHARINDEX to get the location of the / and then do something with the characters after it.
My suggestion would be to use CAST as a DateTime. Please see my example below:
SET language british
DECLARE @varMonth int, @varDay int, @varYear as int
SELECT @varDay = DAY(CAST('4/1/2015' AS datetime))
SELECT @varMonth = MONTH(CAST('4/1/2015' AS datetime))
SELECT @varYear = YEAR(CAST('4/1/2015' AS datetime))
SELECT @varDay AS Day, @varMonth AS Month, @varYear AS Year
正如评论中所建议的那样,使用字符串来存储日期并不是一个好主意。如何在世界不同地区代表日期的方式太多了。
但是如果你坚持这个并且无法改变它,你可以随时使用 CONVERT 将该字符串转换为日期[ ^ ]。
一次您将数据作为日期 [ ^ ]数据类型,获取年,月,日应该没问题。请参阅 SQL日期函数 [ ^ ]
As suggested in the comments, it is not a good idea to use strings to store dates. There are just too many variants of how to represent a date in different parts of the world.
But if you are stuck with this and cannot change it, you can always convert the string to a date using CONVERT[^].
Once you have the data as a date[^] data type, it should be no problem to get the year, month and day. See SQL Date Functions[^]
这篇关于sql server中的子串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文