Skip to content

Commit d3ec6ef

Browse files
authored
Update README.md
1 parent 98daa37 commit d3ec6ef

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed

README.md

+37-4
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,26 @@ Explicit validation to ensure the object, variable or component is in the expect
88
You might want to check if a object already exist before creating it. You can use this patterns for table, procedures or any object in the database.
99
```sql
1010
IF EXISTS (SELECT [object_id] FROM tempdb.sys.objects (NOLOCK) WHERE [object_id] = OBJECT_ID('tempdb.dbo.#<table_name>'))
11-
DROP TABLE #<table_name>;
11+
DROP TABLE #<table_name>;
1212
```
1313

1414
### Check if database exists
1515
Does the database exists and is it up and running?
1616
```sql
1717
IF EXISTS (SELECT CASE WHEN DATABASEPROPERTYEX(name, 'Status') = 'ONLINE' THEN 1 END FROM master.dbo.sysdatabases WHERE name = <db_name>)
18-
PRINT N'<db_name> is available';
18+
PRINT N'<db_name> is available';
1919
```
2020
### Check if is primary node
21-
Check if the current replica of a Availability Group is the primary one.
21+
Check if the current replica of a Availability Group is the primary one. First check if AG is enabled.
2222
```sql
23-
IF sys.fn_hadr_is_primary_replica ('<db_name>') =
23+
IF (SELECT SERVERPROPERTY('IsHadrEnabled')) = 1
24+
BEGIN
25+
IF sys.fn_hadr_is_primary_replica ( @DatabaseName ) = 1
26+
BEGIN
27+
PRINT N'Database is not the primary';
28+
END;
29+
END;
30+
2431
```
2532

2633
### Null or empty
@@ -67,5 +74,31 @@ END CATCH;
6774
### Use the database context
6875

6976
## Data manipulation
77+
### Deleting a large number of rows
78+
It´s a script you can use to purge a large number of rows of a given table. You can start/stop the script freely, it won’t hurt anything. It´s setup to delete 1000 records per loop, but you can change this value based in your needs. The most important thing is to use a loop value which does not cause T-LOG contention.
7079
```sql
80+
BEGIN
81+
SET NOCOUNT, XACT_ABORT ON;
82+
DECLARE @ErrorMessage NVARCHAR(4000), @rows INT;
83+
BEGIN TRY
84+
SET @rows = 1;
85+
WHILE (@rows > 0)
86+
BEGIN
87+
BEGIN TRANSACTION
88+
-- purge data older than 90 days
89+
DELETE TOP(1000) FROM [dbo].[<table_name>] WHERE [LastUpdated] <= DATEADD(M, -3, GETDATE());
90+
SET @rows = @@ROWCOUNT;
91+
COMMIT TRANSACTION;
92+
END;
93+
END TRY
94+
BEGIN CATCH
95+
SELECT @ErrorMessage = ERROR_MESSAGE();
96+
PRINT @ErrorMessage;
97+
IF (XACT_STATE()) = -1
98+
ROLLBACK;
99+
IF (XACT_STATE()) = 1
100+
COMMIT;
101+
THROW;
102+
END CATCH;
103+
END;
71104
```

0 commit comments

Comments
 (0)