close

【SQL Server】SQL Server語法:sqlserver資料存在就更新不存在就插入新資料

 

一、前言

sql server資料庫常用語法分享,

sqlserver資料存在就更新不存在就插入新資料,

這樣一來再自動化資料庫的時候就會很方便~

這也是常用的方法要學起來。

 

進入基本教學前,不要忘了訂閱按讚分享唷!

部落格教學網站:
https://pixnashpython.pixnet.net/blog
想要即時訂閱最新文章:
https://forms.gle/MdXmiF2HgHhNChL46
訂閱Telegram來接收最新資訊:
https://t.me/joinchat/VUUuDt67Uq5l6CIQ

 

 

二、常用語法:sqlserver資料存在就更新不存在就插入新資料


begin tran
if exists (select * from [{symbol}] with (updlock,serializable) where [Date] = '{date}')
begin
   update [{symbol}] set [Date] = '{date}', 
   [Symbol] = '{symbol}', 
   [Open] = {open}, 
   [High] = {high},
   [Low] = {low},
   [Close] = {close},
   [Volume] = {volume} where[Date] = '{date}'
end
else
begin
   insert into [{symbol}] ([Date], [Symbol], [Open], [High], [Low], [Close], [Volume])
   values ('{date}', '{symbol}', {open}, {high}, {low}, {close}, {volume})
end
commit tran

範例解說:主要分成兩段,如果這個資料ID存在就直接用更新的語法,

如果資料不存在就用insert的語法,用{}用起來的部分是我中間摻了python的用法,

{}起來的部分是python要送進來的變數,{symbol}資料表名稱 {date}資料id

還有其他要被我放進資料庫裡面的變數。

 

如果用python當後端可以這樣寫,弄成一個函數會比較方便。

def insert_table_common(self, symbol, date, open, high, low, close, volume, cmt=True):
                    
    sql = f'''
    begin tran
    if exists (select * from [{symbol}] with (updlock,serializable) where [Date] = '{date}')
    begin
       update [{symbol}] set [Date] = '{date}', 
       [Symbol] = '{symbol}', 
       [Open] = {open}, 
       [High] = {high},
       [Low] = {low},
       [Close] = {close},
       [Volume] = {volume} where[Date] = '{date}'
    end
    else
    begin
       insert into [{symbol}] ([Date], [Symbol], [Open], [High], [Low], [Close], [Volume])
       values ('{date}', '{symbol}', {open}, {high}, {low}, {close}, {volume})
    end
    commit tran
    '''
    
    self.cur.execute(sql)
    
    if cmt == True: # auto commite
        self.conn.commit(

 

 

三、後記


SQL真的很好用,入門可以參考這一篇。

【SQL Server】SQL Server教學(一):一次就裝好SQL Server手把手教到會!

https://pixnashpython.pixnet.net/blog/post/37393720

【SQL Server】SQL Server教學(二):限制權限給外部使用者(新增資料庫登入帳號)

https://pixnashpython.pixnet.net/blog/post/50127964

【SQL Server】SQL Server教學(三):SQL SERVER匯出及匯入、備份及還原教學一次學會最完美的搬移方法

https://pixnashpython.pixnet.net/blog/post/50713255

 

部落格教學網站:
https://pixnashpython.pixnet.net/blog
想要即時訂閱最新文章:
https://forms.gle/MdXmiF2HgHhNChL46
訂閱Telegram來接收最新資訊:
https://t.me/joinchat/VUUuDt67Uq5l6CIQ

arrow
arrow

    恩哥Python 發表在 痞客邦 留言(0) 人氣()