SQL時分秒轉為秒


declare @sql varchar(20)
set @sql='37:02:10'

--test--

SELECT substring(@sql,0,charindex(':',left(@sql,3)))
select cast(substring(@sql,0,charindex(':',left(@sql,3))) as int)*3600
+cast(substring(right(@sql,5),0,charindex(':',right(@sql,5))) as int)*60
+substring(right(@sql,5),charindex(':',right(@sql,5))+1,len(right(@sql,5))-charindex(':',right(@sql,5)))

--end test ----


declare @i int
set @i=133330

select cast(@i/3600 as varchar)
       +':'+
       case when len(@i%3600/60)=1 then '0'+cast(@i%3600/60 as varchar) else cast(@i%60/60 as varchar) end
       +':'+
       case when len(@i%60)=1 then '0'+cast(@i%60 as varchar) else cast(@i%60 as varchar) end

/*
37:02:10
*/

declare @sql varchar(20)
set @sql='37:02:10'
--SELECT substring(@sql,0,charindex(':',left(@sql,3)))
select cast(substring(@sql,0,charindex(':',left(@sql,3))) as int)*3600
+cast(substring(right(@sql,5),0,charindex(':',right(@sql,5))) as int)*60
+substring(right(@sql,5),charindex(':',right(@sql,5))+1,len(right(@sql,5))-charindex(':',right(@sql,5)))


 

 

 

 

-----------------------------------------------------------------------------------------------------------------------

由字符串轉化為標准時間

Sql Server將字符串轉換為日期(2006-08-15 10:36:36)轉載 分類: 技巧程序 
在Sql Server中要將字符串轉為日期比如20060815104235轉換為2006-08-15 10:42:35。用cast和convert都提示類型轉換錯誤,cast和convert都需要對應的日期時間格式才能轉換。抓耳撓腮着急之時,一好友給了個函數,結果OK!
 
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
/*
Fun  : 將字符串轉換為時間格式
Author  : YL
Create Time : 2005-7-23
*/
ALTER FUNCTION [dbo].[funStringToDateTime]
 (@strTime varchar(20))  --字符串形式的時間。格式:YYYYMMDDHHMISS --> YYYY-MM-DD HH:MI:SS
RETURNS datetime
AS
Begin
 Declare @strTmp  as varchar(20)
 Set @strTime = ltrim(rtrim(@strTime))
 Set @strTmp = subString(@strTime, 1, 4)    -- "YYYY"
 Set @strTmp = @strTmp + '-'     -- "YYYY-"
 Set @strTmp = @strTmp + subString(@strTime, 5, 2)  -- "YYYY-MM"
 Set @strTmp = @strTmp + '-'     -- "YYYY-MM-"
 Set @strTmp = @strTmp + subString(@strTime, 7, 2)  -- "YYYY-MM-DD"
 Set @strTmp = @strTmp + ' '     -- "YYYY-MM-DD "
 Set @strTmp = @strTmp + subString(@strTime, 9, 2)  -- "YYYY-MM-DD HH"
 Set @strTmp = @strTmp + ':'     -- "YYYY-MM-DD HH:"
 Set @strTmp = @strTmp + subString(@strTime, 11, 2)  -- "YYYY-MM-DD HH:MI"
 Set @strTmp = @strTmp + ':'     -- "YYYY-MM-DD HH:MI:"
 Set @strTmp = @strTmp + subString(@strTime, 13, 2)  -- "YYYY-MM-DD HH:MI:SS"
 
 return cast(@strTmp as datetime)
End
 
如果是這樣的一個字符串"2000年1月2日",用sql語句轉換成"2000-1-2"的標准日期格式
select Replace(Replace(Replace('2000年1月2日','年','-'),'月','-'),'日','')
select Replace(Replace(Replace(字段名,'年','-'),'月','-'),'日','') from table1


/*
CONVERT(NVARCHAR(10), CAST([UPTIME] AS DATETIME),8)
*/
————————————————
版權聲明:本文為CSDN博主「o0wufan0o」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/o0wufan0o/article/details/17376757


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM