sql一些常用的類型轉換、日期、字符串函數


--1.類型轉換convert() cast()
--convert(data_type,expression,[style])
    注意:對於時間轉換,只能用convert()
    print convert(varchar(16),getdate(),120)
--cast(expression as data_type)
print convert(varchar(16),getdate(),120)

--2.union()聯合結果集
--union指的是聯合的意思,是將多個結果聯合成一個結果集,把所有的記錄都
--加起來編程一個大的結果集
--可以union的前提:每個結果集的列的個數都得一致
    --並且多個結果集之間的列的數據類型需要意義對應。    
    --union 使用union的時候默認執行去重復的操作,
    --union all(在不不需要去重的前提下,推薦用這種)因為union要進行重復字掃描,所以效率低
select 商品名稱,SUM(銷售數量*銷售價格)as 銷售總價 from MyOrders group by 商品名稱
union  select '銷售總價',sum(銷售數量*銷售價格)from MyOrders

--3.在一個表中一次性插入多條數據
select * from Contacts
insert Contacts
select '翟群','18721586025','547916475@qq.com',1 union all
select '嘻嘻','1345678901','heh@qq.com',2 union all
select '哈哈','1234567891','163@qq.com',3 union

--4.備份表
select * into MyStudentNew from MyStudent。
--說明:上述sql語句表示復制Mystudent表到MystudentNew表中,但是約束不會被復制。
--如果已經存在一個Mystudent表了,則會報錯。

--5.只復制表結構
select * into MystudentNew1 from MyStudent where 1<>1
select top 0 * from into MyStudentNew1 from MyStudent

--6.將一張表的數據插入另一張已經存在的表中
insert into MyStudentNew2
select isnull(tsname,'匿名學生'),Isnull(tsage,18),tsgender,0,0,tsclassId,isnull(tsbirthday,getdate()) from TblStudent


---------------------------字符串函數--------------------
select len('hi,中華')  --返回字符串中字符的個數 5
select datalength('hi,中華') --返回該字符所占用的字節數 7
select datalength(N'hi,中華') --返回該字符unicode編碼方式的字節數 10

select upper('how are you ') --返回大寫字符串
select lower('HOW ARE YOU')  --返回小寫字符串

print '-------'+ltrim('     hello   ')+'----------' --去掉左邊的空格
print '-------'+rtrim('     hello   ')+'----------' --去掉右邊的空格
print '-------' +trim('     hello   ')+'----------' --去掉兩邊的空格

--substring(value_expression,start_expression,lenght)索引從1開始
print substring('123456',1,3)  --結果為123
print substring('123456',0,3)  --結果為12
print substring('123456',-1,3) --結果為1

print substring('123456',-1,3)

-------------------------日期函數------------------------

getdate() --獲得當前日期時間
print dateadd(year,5,getdate()) --在當前年加上5年,若減五年,寫成-5
print dateadd(month,2,getdate()) --在當前年月加上5月
print dateadd(hour,2,getdate())     --當前時間上加上2個小時

getdiff() --計算兩個日期之間的差
print datediff(year,'2013-12-8 00:00:00.000',getdate()) --年份之差
print datediff(month,'2013-12-9 00:00:00.000',getdate())--月份之差
print datediff(day,'2013-12-9 00:00:00.000',getdate())  --天數之差
print datediff(hour,'2013-12-8 00:00:00.000',getdate()) --時間之差
print datediff(second,'2013-12-8 00:00:00.000',getdate()) --分鍾之差

datepart() --截取日期的某部分
print detepart(weekday,getdate())

print datepart(weekday,getdate())--一周的第幾天
print datepart(week,getdate())   --一年的第幾周
print datepart(month,getdate())     --一年的第幾個月
print datepart(dayofyear,getdate()) --一年的第幾天
print datepart(day,getdate())     --一個月中的

 


免責聲明!

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



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