1. 程式人生 > >【資料庫】SQL 技巧-持續更新

【資料庫】SQL 技巧-持續更新

1.將多個值拼接在同一個欄位裡。

update Common_Customer 
set share_name=( 
select stuff( ( 
select ',' +cs.staff_name 
from 
view_customer cs 
where cs.customer_id=common_customer.customer_id for xml path('')),1,1'') )
where [email protected]


[email protected]@error,用法

@@error是系統函式,當沒有傳送錯誤時返回0,如果發生錯誤時@@error《》0,並返回錯誤號,每個SL語句執行完,@@error值都會變

BEGIN TRAN Tran_Money    --開始事務

DECLARE @tran_error int;
SET @tran_error = 0;
    BEGIN TRY 
        UPDATE tb_Money SET MyMoney = MyMoney - 30 WHERE Name = '劉備';
        SET @tran_error = @tran_error + @@ERROR;
        --測試出錯程式碼,看看劉備的錢減少,關羽的錢是否會增加
        --SET @tran_error = 1;
        UPDATE tb_Money SET MyMoney = MyMoney + 30 WHERE Name = '關羽';
        SET @tran_error = @tran_error + @@ERROR;
    END TRY

BEGIN CATCH
    PRINT '出現異常,錯誤編號:' + convert(varchar,error_number()) + ',錯誤訊息:' + error_message()
    SET @tran_error = @tran_error + 1
END CATCH

IF(@tran_error > 0)
    BEGIN
        --執行出錯,回滾事務
        ROLLBACK TRAN;
        PRINT '轉賬失敗,取消交易!';
    END
ELSE
    BEGIN
        --沒有異常,提交事務
        COMMIT TRAN;
        PRINT '轉賬成功!';
    END

3.sql錯誤處理

begin try
select 2/0
end try

begin catch
select error_number() as error_number ,
error_message() as error_message,
error_state() as error_state,
error_severity() as error_severity
end catch

4.sql server批量更新欄位

update A

set  A.a=B.a

from B 

left join C ON B.b=C.c

where