Getting Current SESSION ID and TRANSACTION ID in MSSQL
To get SESSION ID: select @@spid To get TRANSACTION ID: select CURRENT_TRANSACTION_ID()
To get SESSION ID: select @@spid To get TRANSACTION ID: select CURRENT_TRANSACTION_ID()
"OFFSET FETCH" is a filter that allows skipping a certain number of rows in the result set. For example: select field1, field2, field3 from table1 order by field1, field2 offset 100 rows fetch next 50 rows only; This example will return rows from 101 to 150, from all rows sorted by field1 and field2.
Two Ways to Execute Transactions in MSSQL with Rollback on Error. The First Way: BEGIN TRY BEGIN TRAN UPDATE 1 UPDATE 2 --Error UPDATE 3 COMMIT TRAN END TRY BEGIN CATCH ROLLBACK TRAN END CATCH The Second Way: SET XACT_ABORT ON BEGIN TRAN UPDAT…
Example of searching for a procedure by text that it contains SELECT name FROM sys.procedures WHERE Object_definition(object_id) LIKE '%some_text%' This script will return the names of all procedures that contain the text: "some_text"
Example of Date Range Selection: WITH q AS ( SELECT 1 AS num UNION ALL SELECT num + 1 FROM q WHERE num < 10 ) SELECT DATEADD(DAY,0,cast(cast(DATEADD(DAY,-num,SYSDATETIME()) as date) as datetime)) FROM q Simple version of the example of selecting a range of numbers:
Example of updating data in one table with simultaneous comparison and condition check based on the second table using JOIN: update cc set cc.ActivateState=2 from ClientsCards cc left join ClientsCardsHeads cch on cch.CardUid=cc.Uid wher…
This example can be useful when you need to choose a certain number of numbered records from somewhere and insert them into a temporary table or table variable. Example: select number as Section from master..spt_values where type='L'…
Example of how to catch errors in MSSQL. BEGIN TRY -- Some code that will return an error for example. SELECT 1/0; END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber ,ERROR_SEVERITY() AS ErrorSeverity ,ERROR_STATE() AS ErrorState ,ERROR_PROCEDURE() AS ErrorProcedure ,ERROR_LINE() AS ErrorLine ,ERROR_MESSAGE() AS ErrorMessage; END CATCH