European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

SQL Server Hosting - HostForLIFE :: The Complete Reference - Table Scan, Index Scan, And Index Seek

clock September 17, 2021 07:18 by author Peter

In this article, you will see the Complete Reference - Table Scan, Index Scan, and Index Seek in MSSQL.

Background
While working with MS SQL database and SQL, a good knowledge of how the index works and how to use them to improve the SQL query performance is very important.

Prerequisites
Preliminary understanding is required about what the index is and how to create and drop an index.

Difference between Scan and Seek Operation


Scan Operation Seek Operation
1. Fetches All the rows from the table Selective rows from the table
2. Touches Every single row of the table is either required or not Only the required or matching row
3. CPU Consumption More Less
4. I/O Component Usage More Less
5. Executes with SELECT statement WHERE clause

Table and Index Access
Now, let us understand each one, one by one, with practical examples.

Table Scan

  • It is a very simple process. While performing table scan, the query engine starts from the physical beginning of the table and it goes through every row into the table. If a row matches with the criteria then it includes that into the result set.
  • It is the fastest way to retrieve the data especially when there is quite a small table.
  • For a small table, a query engine can load all the data in a one-shot but from a large table it is not possible i.e. more IO and more time will be required to process those large data.
  • Generally, a full table scan is used when a query doesn’t have a WHERE clause i.e. all data.

For example, an Employee table with no index and the following query will use the Table scan.
SELECT * FROM Employee

Index Scan

  • When you have a clustered index and your query needs all or most of the records (i.e. query without where or having clause) then it uses an index scan.
  • Index scan works similar to the table scan during the query optimization process. The query optimizer takes look at the available index and chooses one of the best, based on JOINs and WHERE clauses.
  • As the right index is being chosen, the SQL query processing engine will navigate the tree structure to the pointer of the data which matches the criteria and further extracts only the needed/required records.
  • The key difference between Table Scan and Index Scan is that data is stored in the index tree, the query processor knows it when reaches the end of the current it is looking for. Then it can send the query or move on to the next range of data.
  • An index scan is slightly faster than the Table scan but significantly slower than an Index.

For example, Employee table with clustered index and the following query will use the Index scan,

SELECT * FROM Employee

Index Seek

  • When the search criterion matches the index well enough which can navigate directly to particular points into the data, this is known as the Index seek.
  • The index seeks the fastest way to retrieve the data in the database.
  • For example, the following query will use the Index seek which can be confirmed by checking the execution plan of the query
  • The query optimizer can use an index directly to go to the 3rd employee id and fetch the data.

Query execution plan can show the same as it uses an index seek through created EmployeeId index,

SELECT name FROM Employee WHERE id=5


Difference between Table Scan, Index Scan and Index Seek

Table Scan Index Scan Index Seek
1. Used when? Used when we need to retrieve all the data such as 90% to 100% Used when we need to retrieve some data based on some condition such as 10% of data
2. WHERE clause The query doesn’t have a WHERE clause and the Table doesn't have clustered index then a full Table Scan is used The query doesn’t have a WHERE clause and the Table have clustered index then Index Scan is used
3. Table and Index The table is slower than the Index The index is faster than Table
4. Scan and Seek The scan is slower than Seek Seek is faster than Scan

Now, I hope you understand the key important things about Table Scan, Index Scan, and Index Seek in MSSQL.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



SQL Server Hosting - HostForLIFE :: Full And Differential Backup Using SSMS

clock September 14, 2021 10:16 by author Peter

In this article, we will see 'how to create a SQL Server Database backup'. Database backup using SQL Server Management Studio, SQL Server provides a large number of options to create backups. We will discuss here FULL BACKUP and DIFFERENTIAL BACKUP.
 
FULL BACKUP
The most common type of backup is the full backup. In this type of backup, it creates a full backup of your database and also includes the transaction logs into the backup.
 
We can create it by using SSMS (SQL Server Management Studio).
 
Let's see how.
 
Full Backup using T-SQL (Transact-SQL)
This will create a full (Complete) backup into the .bak file of the given database,
BACKUP DATABASE DotNet TO DISK='D:\DotNet\Backup\DotNet.BAK'
 
Full Backup using SSMS
Open your SSMS and select the desired database and right-click on the database name click on Tasks > Back Up,

Select Full as Backup Type, select Disk as the destination, and then click on Add button to add the directory where the backup will be stored on your disk.

Select the destination for the backup,

Click on ok and again ok on the next screen and the backup progress will be started.


This process will take some time that depends upon your database size.
 
DIFFERENTIAL BACKUP
Another option to create a backup is Differential backup. Differential Backup is the backup of the changes that have been made after a recent full/ complete database backup.
 
Let's see how.
 
Differential Backup using T-SQL (Transact-SQL)
This will create a differential backup with .DIF file extension of the given database,
 
BACKUP DATABASE DotNetKida TO DISK='D:\DotNet\Backup\DotNet.DIF' WITH DIFFERENTIAL
 
Differential Backup using SSMS
Open your SSMS and select the desired database and right-click on the database name click on Tasks > Back Up,

Select Differential as Backup Type, select Disk as the destination, and then click on Add button to add the directory where the backup will be stored on your disk.


Select the destination for the backup,


Click on ok and again ok on the next screen and the backup progress will be started.


This process will take some time and will depend upon your database size.

Some Notable Points

  • The Backup statement is not allowed in an implicit or explicit transaction.
  • Backups created by the recent version or higher of SQL Server cannot be restored in earlier or lower version of SQL Server.
  • Check the size of a full database backup by using the sp_spaceused.
  • For a large database, the process may take more time and more disk space consider a full database backup with a series of differential database backups.
  • Creating a new differential backup always requires a recently full database backup. If the database has never been backed up, then first you have to run a full database backup before creating any differential backups.
I hope this will help you to create a backup of the SQL Server database.

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: Export Blob(BINARY or VARBINARY) From SQL Table And Save It As A File

clock September 7, 2021 08:41 by author Peter

A binary value or type in SQL Server is a series of bytes (known as a byte array in some programming languages). Just like char/varchar, there are fixed-length types, binary(1-8000), and variable-length ones, varbinary(1-8000) and varbinary(max).
Sometimes we store this type of data in SQL Tables and lose the source files. This type of data is stored in a binary format which is system formatted.
 
A PDF file is converted and stored in this format. And the text looks similar to this,
 "0x255044462D312E340A25C3A4C3BCC3B6C39F0A322030206F626A0A3C3C2F4C656E67746820332030
20522F46696C7465722F466C6174654465636F64653E3E0A73747265616D0A789C358CBD1240401083FB
7D8AD48A75B71CABD728551EC0F8291C43E3F5ED0D26453"

 
Now to recreate a file from this data is not something that can be created by simple copy-paste.
 
Here is the process which can be used to get the source file.
DECLARE @outPutPath varchar(50) = 'C:\ExtractedFiles'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [FileName]  varchar(100), [Doc_Content] varBinary(max) )

INSERT INTO @Doctable( [FileName],[Doc_Content])
Select [RecordID],[FileUpload] FROM  [dbo].[tbl_AuthorConferenceList]

--SELECT * FROM @table

SELECT @i = COUNT(1) FROM @Doctable

WHILE @i >= 1
BEGIN

       SELECT
        @data = [Doc_Content],
        @fPath = @outPutPath +  '\' +[FileName] +'.pdf',
        @folderPath = @outPutPath
       FROM @Doctable WHERE id = @i

  --Create folder first

  EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instance created
  EXEC sp_OASetProperty @init, 'Type', 1;
  EXEC sp_OAMethod @init, 'Open'; -- Calling a method
  EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
  EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
  EXEC sp_OAMethod @init, 'Close'; -- Calling a method
  EXEC sp_OADestroy @init; -- Closed the resources

  print 'Document Generated at - '+  @fPath

--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END

Now you might end up getting compilation issues.
 
The reason is all the System Stored Procedures are unavailable.
To solve this we have to enable the Facets Property "OleAutomatedEnabled"

 

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: Types Of SQL Injection

clock August 30, 2021 07:46 by author Peter

This article is going to focus on the different types of SQL Injection attack methods. In a previous article, we took an introductory approach to SQL Injection and simply listed the types of SQL Injection and we managed to look at some examples of SQL injection. This time we will dive into the types of SQL Injection as well as try to give real-world examples of each type.
 
SQL Injection is a popular malicious attack on websites and web applications which involves the use of SQL statements through user input. SQL Injection may be used to tamper with organizational sensitive data, identity theft and exposing organizational sensitive data. This may result in financial loss to organizations or reputational damage of the organization or the web application/website.
 
Types of SQL Injections
The three different categories of SQL Injection are,
    In-band (Classic)
    Inferential(Blind)
    Out-of-Band

In-band Injection
Error-based SQLi and Union-based SQLi are the most commonly used In-band SQLi. In-band SQLi entails that an attack is launched and the attacker uses the same channel to obtain results.
 
Error-based SQLi
The user intentionally adds characters such as ‘,”,/*, etc to the input to invoke an error from the application


Then if you go on the code-behind file, you might find code like this,

    Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("Constring").ConnectionString)  
    Using cmd1 = New SqlCommand("select  from tbl_users where user_login='" +  user_login + "'", con)  


Notice that the server shows the user the error in syntax ‘from’ hence the attacker may use these prompts to launch an attack.


If the attacker replaces the username with,

    'OR '1'='1';Select @@version  --'  

Notice how the attacker obtains database information using the In-band method of injection and he may make use of the error dialogs to view information about the internal details of the database and may end up deleting some data.  

Union-based SQLi
As the name suggests this method makes use of the UNION SQL operator, which combines two statements. When using the SQL, UNION operator the SELECT statements must be similar, with the same number of columns and having same data types.
 
Example

i.e. SELECT user_id,user_login,password,user_type FROM customers UNION SELECT perm_id,username,password,role from Sys_Permissions 

Once an attacker has got information about the database using the @@version keyword it is easier for them to now execute UNION statements trying out various table names and column combinations.
 
Inferential SQLi (Blind)
Inferential SQLi has two groups namely the Boolean-based and Time-based. They rely on the response from the server, which means it is a trial and error exercise. The attacker sends payloads to the server, waits for a response this, and is never sure of the execution of the SQL query thus the name "Blind". Unlike In-band, the attacker does not get the data from the website database.
 
Boolean-based Injection
The attacker needs to send values to the server and the server response is either TRUE/FALSE. In Boolean-based the attackers normally depend on guessing and that is why it takes a large amount of time. Unlike with In-band Injection, there is no direct response or result that the execution has been successful. The attacker has to guess number of columns and column names in the table and the underlying query, which is executing the requests. An example of Boolean-based Injection is given below,
 
Example
http://MyShopOnline/Products/?id=4401 or 1=1
 

This means the underlying query at the server-side will be as follows and this may return a TRUE/FALSE response.
    Select * from Para_Products where prodid='2 ' OR '1'='1' --;   

Depending on the backend database, the database connection settings, and operating system an attacker can achieve to read, update, or delete arbitrary data/tables from the database.
 
The user may start by sending an SQL statement, which he knows, will return False such as 1=0, and take note of the response. He will then use this false response to determine his trial once he gets any response that is different from the latter.
 
Time-based Injection
In Time-based SQL Injection the attacker uses an SQL query to force the database to wait for a given length of time before in sends a response. The attacker uses this response time to determine his success.
 
Example
    Select * from Para_Products where prodid='2 '  OR '1'='1'   WAITFOR DELAY '0:0:5'   --;   

The time factor is used by utilizing the WAITFOR DELAY operator.
 
Out-of-band Injection
Out of the three Injection Types is the least common type of Injection. Unlike In-band, when using this method it does not use the same channel to obtain information, instead it uses DNS/HTTP protocol. This means that the web application being attacked must not have any security parameters to deny DNS or HTTP outbound requests. Out-of-band is faster than Inferential attacks.
 
These are the main types of SQL Injection and in later articles; we will look at SQL Injection Protection Methods, other injection flaws, etc. 

HostForLIFEASP.NET SQL Server 2019 Hosting

 



SQL Server Hosting - HostForLIFE :: Performance Tip And Tricks For SQL Sever DB Objects

clock August 23, 2021 07:37 by author Peter

Below are some tips on how to improve the performance of SQL DB objects which need to be followed while creating or modifying any DB objects.

Add Nolocks

No lock should be added to all select statements and while joining multiple tables when those tables are used by multiple pages or applications. It is advisable not to use Nolock on temp tables and Views.

Ensure No Table Scan

Ensure there is no table scan. Check this in the execution plan on SQL Server. The table scan can be avoided by using indexed columns on join conditions

Join and Update should happen on Primary Key Column

Avoid join of two tables on columns other than the primary key column /indexed column. Update also should happen on update key condition.

Select Only required Columns 

To reduce performance issues for queries that return heavy data use only required columns instead of all on the select statements.

Use Column Names in Insert Query

When inserting to a table that is more frequently used by multiple applications and which has heavy data specify column names to reduce performance issues.

Use Table Alias in Join query

Using table alias in join query helps reducing performance issues in lengthy stored procedures.

Query Optimization By SQL Indexes

Indexes improve search operation and reduce table scan hence improves performance. So it is always advised to use indexed columns for joins, select query filter conditions. Indexes somehow reduce the performance of the insert operation hence while creating indexes on the temp table it's a good practice to create it post data insertion to the temp table.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



SQL Server Hosting - HostForLIFE :: Cursors In SQL Server

clock August 20, 2021 10:17 by author Peter

A SQL cursor is a database object that is used to retrieve data from a result set one row at a time. A SQL cursor is used when the data needs to be updated row by row. This article explains everything about SQL cursors. In this article, we will learn the following

SQL Cursor Life Cycle

The following steps are involced in a SQL cursor life cycle.

    Declaring Cursor
    A cursor is declared by defining the SQL statement.
     
    Opening Cursor
    A cursor is opened for storing data retrieved from the result set.
     
    Fetching Cursor
    When a cursor is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.
     
    Closing Cursor
    The cursor should be closed explicitly after data manipulation.
     
    Deallocating Cursor
    Cursors should be deallocated to delete cursor definition and release all the system resources associated with the cursor.

Why use a SQL Cursor?
In relational databases, operations are made on a set of rows. For example, a SELECT statement returns a set of rows which is called a result set. Sometimes the application logic needs to work with one row at a time rather than the entire result set at once. This can be done using cursors.

In programming, we use a loop like FOR or WHILE to iterate through one item at a time, the cursor follows the same approach and might be preferred because it follows the same logic.
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
 [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ] FOR select_statement
 [ FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]

Cursor Example
The following cursor is defined for retrieving employee_id and  employee_name from Employee table. The FETCH_STATUS value is 0 until there are rows. When all rows are fetched then  FETCH_STATUS becomes 1.
use Product_Database
SET NOCOUNT ON;


DECLARE @emp_id int ,@emp_name varchar(20),
    @message varchar(max);

PRINT '-------- EMPLOYEE DETAILS --------';

DECLARE emp_cursor CURSOR FOR
SELECT emp_id,emp_name
FROM Employee
order by emp_id;

OPEN emp_cursor

FETCH NEXT FROM emp_cursor
INTO @emp_id,@emp_name

print 'Employee_ID  Employee_Name'

WHILE @@FETCH_STATUS = 0
BEGIN
    print '   ' + CAST(@emp_id as varchar(10)) +'           '+
        cast(@emp_name as varchar(20))


    FETCH NEXT FROM emp_cursor
INTO @emp_id,@emp_name

END
CLOSE emp_cursor;
DEALLOCATE emp_cursor;

What are the limitations of a SQL Cursor?

A cursor is a memory resident set of pointers -- meaning it occupies memory from your system that may be available for other processes.
Cursors can be faster than a while loop but they do have more overhead.

Another factor affecting cursor speed is the number of rows and columns brought into the cursor. Time how long it takes to open your cursor and fetch statements.
Too many columns being dragged around in memory, which are never referenced in the subsequent cursor operations, can slow things down.

The cursors are slower because they update tables row by row.

How can we replace SQL Cursors?

There's one replacement for cursors in SQL server joins.

Suppose we have to retrieve data from two tables simultaneously by comparing primary keys and foreign keys. In these types of problems, the cursor gives very poor performance as it processes through each and every column. On the other hand using joins in those conditions is feasible because it processes only those columns which meet the condition. So here joins are faster than cursors.

The following example explains the replacement of cursors through joins.

Suppose, we have two tables, ProductTable and Brand Table. The primary key of BrandTable is brand_id which is stored in ProductTable as foreign key brand_id. Now suppose, I have to retrieve brand_name from BrandTable using foreign key brand_id from ProductTable. In these situations, cursor programs will be as follows,
use Product_Database
SET NOCOUNT ON;

DECLARE @brand_id int
DECLARE @brand_name varchar(20)


PRINT '--------Brand Details --------';

DECLARE brand_cursor CURSOR FOR
SELECT distinct(brand_id)
FROM ProductTable;

OPEN brand_cursor

FETCH NEXT FROM brand_cursor
INTO @brand_id

WHILE @@FETCH_STATUS = 0
BEGIN
    select brand_id,brand_name from BrandTable where brand_id=@brand_id
--(@brand_id is of ProductTable)

    FETCH NEXT FROM brand_cursor
INTO @brand_id

END
CLOSE brand_cursor;
DEALLOCATE brand_cursor;


The same program can be done using joins as follows,

Select distinct b.brand_id,b.brand_name from BrandTable b inner join
ProductTable p on b.brand_id=p.brand_id


As we can see from the above example, using joins reduces the lines of code and gives faster performance in case huge records need to be processed.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



SQL Server Hosting - HostForLIFE :: SQL Aggregate Statement

clock August 16, 2021 08:22 by author Peter

The Aggregate function is used to perform calculations on a set of values and return a single value, ignoring all null values. The Aggregate functions are often used with the group by clause of the select statement in SQL. The database management aggregate function is a function in which the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning
 
All aggregate statements are deterministic In other words, aggregate functions return the same value each time that they are called when called with a specific set of input values.
 
See Deterministic and Nondeterministic Functions for more information about function determinism The over clause may follow all aggregate functions, except the STRING_AGG, grouping or GROUPING_ID functions
 
Aggregate functions can we use the expressions only in the following situations
    The select list of a select statement (either a subquery or an outer query).
    A having clause.

Functions 

SQL provides the following aggregate functions based off of the following Student table
 
Syntax
   SELECT * FROM Student;

Example

APPROX_COUNT_DISTINCT()
This statement returns the approximate number of unique non-null values in a group.
 
Approx_count_distinct expression evaluates an expression for each row in a group, and returns the approximate number of unique non-null values in a group.
 
This function is designed to provide aggregations across large data sets where responsiveness is more critical than absolute precision.
 
Approx_count_distinct is designed for use in big data scenarios and is optimized for the following conditions

    Access of data sets that are millions of rows or higher and
    Aggregation of a column or columns that have many distinct values

This function implementation guarantees up to a 2% error rate within a 97% probability. Approx_count_distinct requires less memory than an exhaustive count distinct operation, given the smaller memory footprint
 
Approx_count_distinct is less likely to spill memory to disk compared to a precise count distinct operation.
 
To learn more about the algorithm used to achieve this, see hyperloglog.
 
Syntax
    SELECT Count (StudentId) AS Approx_Distinct_OrderKey        
    FROM Student;     

Example

AVG () 
The AVG>statement calculates the average of non-null values in a set.  
The AVG is the data type of expression is an alias data type, the return type is also of the alias data type.
However, if the base data type of the alias data type is promoted, for example from tinyint to int, the return value will take the promoted data type, and not the alias data type
AVG () computes the average of a set of values by dividing the sum of those values by the count of nonnull values
 
If the sum exceeds the maximum value for the data type of the return value, AVG() will return an error. AVG is a deterministic function when used without the over and orderby clauses. It is nondeterministic when specified with the over and order by clauses. for more information.
 
Syntax
    SELECT AVG(StudentAge) FROM Student;      

Example


CHECKSUM_AGG()
This statement returns the checksum of the values in a group. CHECKSUM_AGG ignores null values.
The over clause can follow CHECKSUM_AGG
CHECKSUM_AGG can detect changes in a table
The CHECKSUM_AGG result does not depend on the order of the rows in the table. Also, CHECKSUM_AGG functions allow the use of the Distinct keyword and the Group By clause
 
If an expression list value changes, the list checksum value list will also probably change. However, a small possibility exists that the calculated checksum will not change
 
Syntax   

    SELECT CHECKSUM_AGG(CAST(StudentID AS int))          
    FROM Student;          
    GO  

Example  

COUNT()  
It is used to count the number of rows returned in a select statement.
Count function returns the number of items found in a group. count  operates like the COUNT_BIG function
These functions differ only in the data types of their return values.
Count always returns an int data type value.COUNT_BIG always returns a bigint data type value.
 
Syntax
    SELECT COUNT (StudentName) from Student   

Example  

COUNT_BIG ()
This statement returns the number of items found in a group.COUNT_BIG operates like the count function. These functions differ only in the data types of their return values.
COUNT_BIG always returns a bigint data type value. Count always returns an int data type value. 
The COUNT_BIG(*) returns the number of items in a group. This includes null values and duplicates.
The  COUNT_BIG (all expression) evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT_BIG (distinct expression) evaluates expression for each row in a group, and returns the number of unique, nonnull values.
 
Syntax
    SELECT COUNT(*)          
    FROM Student          
    GO     

Example 

GROUPING ()
The Grouping statement indicates whether a specified column expression in a Group by  list is aggregated or not Grouping returns 1 for aggregated or 0 for not
 
Aggregated in the result set. Grouping can be used only in the SELECT <select> list, HAVING and ORDER BY clauses when group by is specified.
 
Grouping is used to distinguish the null values that are returned by Rollup, cube or Grouping sets from standard null values.
 
The null returned as the result of a Rollup, Cube or grouping sets operation is a special use of null. This acts as a column placeholder in the result set and means all.
 
Syntax
    SELECT GROUPING(StudentName) AS 'Grouping'          
    FROM Student          
    GROUP BY StudentName  WITH ROLLUP;          
    GO 
 

 Example


GROUPING_ID statement ()
This function computes the level of grouping. GROUPING_ID can be used only in the SELECT <select> list, HAVING, or ORDER BY clauses when GROUP BY is
specified.
 
Syntax
    SELECT GROUPING_ID(StudentId, StudentName)          
    FROM Student           
    GROUP BY CUBE(StudentId, StudentName)   

Example

In this article, you learned how to use a SQL Aggregate statement with various options.

HostForLIFEASP.NET SQL Server 2019 Hosting

 

 



SQL Server Hosting - HostForLIFE :: Customized Auditing In SQL For DDL Operations At Server Level

clock August 10, 2021 09:04 by author Peter

In this article, we will learn how to implement the Audit feature in SQL server. This includes storing all the Audit information in a local table with respect to operations such as creating, altering, and dropping of all tables at the server level.
 
Why is Auditing essential?
Auditing is indeed required to keep track of all the changes to objects that took place within your SQL Server. It has all information such as event type, changed time, server name, login name, database name, object name and actual SQL script used to make the change.
 
How to achieve Auditing in SQL?
To capture DDL activities locally, you need to achieve the below steps,
    Creation of Trigger
    We need to create a trigger for all DDL activities such as Create, Alter and Drop operations at server level.

    Use of Event Data function
    This function helps to capture data associated with a DDL operation in an XML form which will be later used to store in a local table.

    Creation of a local Audit table
    We will be using a local table to store Audit data from the data returned by EventData function.

    Creation of Stored procedure
    A simple stored procedure is required to capture audit data into an XML parameter using EventData function and storing the same data into the local Audit table.

Detailed steps with SQL query to perform Auditing
 
First, we will create a local table named ‘AuditChanges’ to capture Audit changes into it using the below SQL script,
    CREATE TABLE [dbo].[AuditChanges]  
    (  
        [DatabaseName] [nchar](50) NULL,  
        [TableName] [nchar](50) NULL,  
        [EventType] [nchar](50) NULL,  
        [LoginName] [nchar](50) NULL,  
        [SchemaName] [nchar](50) NULL,  
        [SQLCommand] [nchar](50) NULL,  
        [CaptureTime] [nchar](50) NULL  
    )   


Now we have to create a trigger named ‘Audit_Trigger’ on server level which will store the event data as well as storing the information into AuditChanges table. Here [1] refers to the top 1 and datatype varchar means we are storing it into string.
    ALTER Trigger Audit_Trigger  
    ON ALL SERVER  
    FOR Create_Table, Alter_Table, Drop_Table  
    As Begin  
    DECLARE @EventData XML  
    SELECT @EventData = EVENTDATA()  
    INSERT INTO Test.dbo.AuditChanges  
    (DatabaseName, TableName, EventType, LoginName, SchemaName, SQLCommand, CaptureTime)  
    Values   
    (  
       @EventData.value('(/EVENT_INSTANCE/DatabaseName)[1]','varchar(50)'),  
       @EventData.value('(/EVENT_INSTANCE/ObjectName)[1]','varchar(50)'),  
       @EventData.value('(/EVENT_INSTANCE/EventType)[1]','varchar(50)'),  
       @EventData.value('(/EVENT_INSTANCE/LoginName)[1]','varchar(50)'),  
       @EventData.value('(/EVENT_INSTANCE/SchemaName)[1]','varchar(50)'),  
       @EventData.value('(/EVENT_INSTANCE/TSQLCommand)[1]','varchar(50)'),  
       GETDATE()  
    )  
    END  


All setup is  done. Now we will be creating a table named 'Student' to verify if event data relating to its creation is getting stored in AuditChanges table or not. Below is the query to create the table student.
    CREATE TABLE [dbo].[Student]  
    (  
        [ID] [int] IDENTITY(1,1) NOT NULL,  
        [Name] [char](50) NULL  
    )  

Now as soon as the table is created, its event data will be stored in AuditChanges. Query the Audit table to get the result. As seen below, the Audit table has successfully captured the Student dbo creation details.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



SQL Server Hosting - HostForLIFE :: How to put a SQL Server Database into Recovery Pending?

clock August 2, 2021 06:52 by author Peter

You might be asking why on earth would you want to get a database into an undesirable state, more specifically into a Recovery Pending state.  Well, in my case, I had a client database that had entered into this state due to a failure of storage.  Thankfully, this database was not being used for production, so I had some time to determine the best way to fix the issue.

A phrase that was often used during my time in the fire service, was "Try Before You Pry".  Does the front door of the house need to be kicked in?  It may be unlocked and by trying before prying (with my boot) I can prevent damage to the door.  In these types of scenarios, this philosophy holds true.  Try things out on non-critical databases will help prevent any further damage.

In this instance, I want to try it before forcing something that might be damaging.  This meant I had to get a test database into a recovering state.  Once it is in the state I need, then I can attempt different methods to recover the database properly.  Once a successful solution is determined, I can then confidently pry against the damaged database in production knowing that I am using a validated solution.

DISCLAIMER: DO NOT DO THIS ON A PRODUCTION SQL SERVER INSTANCE.

You have been warned.

DISCLAIMER: DO NOT DO THIS ON A PRODUCTION SQL SERVER INSTANCE.

You have been warned. Again.
How do you get a database into a recovery pending state?

Here is how I did this:

    Start a new transaction.
    Create a new table.
    Stop the SQL Server service
    Rename/Delete the database log file.
    Restart the SQL Server Service

The database will be in a recovery pending state upon the restart of the SQL Server service.
Why is the database in recovery pending?

When the database attempts to come back online, it will be put into a recovery pending state because the log file is not present but there was an open transaction when the service was shut down.  In normal operations, even with an open transaction, SQL Server would go through the recovery phase of the transaction log.  In the rollback phase of recovery, SQL Server would attempt to rollback and transaction that was open at the point of restart and undo the changes.  Since the log file no longer exists, it is unable to do so.

Therefore, the database is now in the recovery pending status.  It’s pending recovery because there was an open transaction, but SQL Server is unable to bring the database into a consistent state.


When this occurs, you will see something like this in the error log:

If the database is shut down cleanly and the transaction log file remove/renamed/etc., SQL Server will just rebuild the log file for you.

Summary

 

Sometimes it is useful to be able to put a database into a specific state of being so that you can validate solutions before attempting to perform an action in a Production environment.  Just remember to try it before prying it.  Not doing so could just make things worse so being overly cautious is not a bad thing.

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: CROSS JOIN In SQL

clock July 27, 2021 08:12 by author Peter

In this blog, we will see how to use 'CROSS JOIN In SQL'. When each row of Table 1 is merged within each row of Table 2, then it's called a CROSS JOIN or Cartesian Join or in simple words, we can say that like CROSS JOIN it always returns the Cartesian product of the sets of the record from (another two or more tables) joined table.

We can write it with a comma-separated table name in order to achieve the same result or we can just write CROSS JOIN just like INNER JOIN without where clause,
SELECT TABLE1.Name, TABLE1.Age, TABLE2.ProjectName,TABLE2.DoA
FROM [EmpTable] AS TABLE1, [Projects] AS TABLE2
OR
SELECT TABLE1.Name, TABLE1.Age, TABLE2.ProjectName, TABLE2.DoA
FROM [EmpTable] AS TABLE1 CROSS JOIN [Projects] AS TABLE2


Let's consider the following two tables,
Table 1 - EmpTable

 

Table 2 - Projects
Now it's time to see the result. As we already know in CROSS JOIN, each row from Table 1 merged (joins/combined) with all rows of Table 2 (other tables / joined tables ) if Table 1 is having X number of rows and Table 2 having some Y number of rows then the result will be X * Y number of rows.

Now it's time to see the result. As we already know in CROSS JOIN, each row from Table 1 merged (joins/combined) with all rows of Table 2 (other tables / joined tables ) if Table 1 is having X number of rows and Table 2 having some Y number of rows then the result will be X * Y number of rows.

HostForLIFEASP.NET SQL Server 2019 Hosting



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in