最近做了三個(gè)問(wèn)題,雖然很小,而且實(shí)現的也略顯笨拙,但還是想記錄下來(lái),供大家參考一下,也滿(mǎn)足一下自己的一種虛榮心,呵呵:)
問(wèn)題一:
要求對一表中的字符數據進(jìn)行自動(dòng)編碼,基本要求大概是:第一條數據編碼為‘FM00000‘,第二條為‘FM00001‘,第三條為"FM00002‘,以次類(lèi)推;剛好最近在練習寫(xiě)觸發(fā)器,簡(jiǎn)單實(shí)現了一下.
實(shí)現思路:
建立主鍵為identity的表,利用表主鍵的identity屬性,在觸發(fā)器中拼成所需字符串,當向表insert數據時(shí)更新相應字段值
--建表
CREATE TABLE [dbo].[test_table] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[NAME] [varchar] (80)
) ON [PRIMARY]
GO
--建立觸發(fā)器
CREATE trigger test_trigger on test_table
for insert
as update test_table
set name =substring(‘FM‘+stuff(‘00000‘,5-len(i.id)+1,len(i.id),CAST(i.id AS char(5))),1,7)
from inserted i where i.id=test_table.id
GO
--測試插入語(yǔ)句
insert into test_table select 1 union select 2 union select 3 union select 4 union select 5
如不使用identity的字段上面的觸發(fā)器也可以做修改,如下:
alter trigger test_trigger on test_table
for insert
as
declare @next_seq int
select @next_seq=(select cast ((select substring(max(name),3,5) from test_table) as int)+1)
update test_table
set name =substring(stuff(‘FM00000‘,7-len(@next_seq)+1,len(@next_seq),cast(@next_seq as char(5))),1,7)
--或者如此,這樣更簡(jiǎn)單:
-- set name =‘FM‘+right(‘00000‘+cast(@next_seq as varchar),5)
from inserted i where i.id=test_table.id
GO
問(wèn)題二:
查詢(xún)中實(shí)現對價(jià)格等貨幣值格式化為$0,000.00樣式的問(wèn)題,實(shí)現如下:
貨幣轉換:
select ‘$‘+convert(varchar,cast(tb字段 as money),1)
示例: select ‘$‘+convert(varchar,cast(111111.5 as money),1)
問(wèn)題三:
編寫(xiě)觸發(fā)器,對一表中插入的日期數據修改為該日期所處月份的最后一天
腳本如下:
--建測試表
create table test_table (
id int IDENTITY(1,1) primary key,
mytime datetime NOT NULL)
GO
--建觸發(fā)器
create trigger date_change_trigger on test_table
for insert
as
update test_table
set mytime = (select dateadd(ms,-3,dateadd(m,datediff(m,0,(select mytime from inserted))+1,0)))
from inserted i where test_table.id=i.id
GO
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。