Thursday, September 5, 2019

How to use NTILE(), CUME_DIST (), PERCENT_RANK() functions

DECLARE @empDept AS TABLE (empID INT IDENTITY(1,1), firstName VARCHAR(250), lastName VARCHAR(250), Department VARCHAR(250), rate DECIMAL(9,2))

INSERT INTO @empDept (firstName, lastName, Department, rate) 
VALUES
 ('Hima', 'Arifin'          ,'Document Control',       17.7885)  
,('James', 'Norred'          ,'Document Control',       16.8269)  
,('Saket', 'Kharatishvili'   ,'Document Control',       16.8269)  
,('Hung', 'Chai'            ,'Document Control',       10.25  )  
,('Kethrine', 'Berge'           ,'Document Control',       10.25  )  
,('Tim', 'Trenary'         ,'Information Services',       50.4808)  
,('Pole', 'Conroy'          ,'Information Services',       39.6635)  
,('Andrew', 'Ajenstat'        ,'Information Services',       38.4615)  
,('Jack', 'Wilson'          ,'Information Services',       38.4615)  
,('Mohit', 'Sharma'          ,'Information Services',       32.4519)  
,('Lara', 'Connelly'        ,'Information Services',       32.4519)  
,('Peter', 'Berg'            ,'Information Services',       27.4038)  
,('Lune', 'Meyyappan'       ,'Information Services',       27.4038)  
,('Jamy', 'Bacon'           ,'Information Services',       27.4038)  
,('Walter', 'Bueno'           ,'Information Services',       27.4038)  

--SELECT * FROM @empDept

SELECT FirstName, LastName, Department, rate
, NTILE(5) OVER(PARTITION BY Department ORDER BY rate DESC) AS Quartile
FROM @empDept

SELECT edh.Department, edh.LastName, edh.Rate,  
       CUME_DIST () OVER (PARTITION BY edh.Department ORDER BY edh.Rate) AS CumeDist,  
       PERCENT_RANK() OVER (PARTITION BY edh.Department ORDER BY edh.Rate ) AS PctRank 
FROM @empDept AS edh 
    INNER JOIN @empDept AS e   
    ON e.empID = edh.empID 
WHERE edh.Department IN (N'Information Services',N'Document Control')  
ORDER BY edh.Department, edh.Rate DESC;

How to use LEAD) and LAG() functions

DECLARE @sales AS TABLE (BusinessEntityID INT, QuotaDate Date,   SalesQuota DECIMAL(9,2))

INSERT INTO @sales (BusinessEntityID, QuotaDate,   SalesQuota) 
VALUES
 (275 , '01-Jan-2005' ,  367000.00  )
,(285 , '01-Jan-2005' ,  556000.00  )
,(275 , '01-Jan-2007' ,  502000.00  )
,(285 , '01-Jan-2006' ,  550000.00  )
,(275 , '01-Jan-2006' ,  1429000.00 )
,(275 , '01-Jan-2010' ,  1324000.00 )
,(285 , '01-Jan-2005' ,  756000.00  )
,(275 , '01-Jan-2007' ,  402000.00  )
,(275 , '01-Jan-2008' ,  950000.00  )
,(275 , '01-Jan-2006' ,  1829000.00 )
,(275 , '01-Jan-2006' ,  114000.00 )

SELECT * FROM @sales --WHERE BusinessEntityID = 275
ORDER BY YEAR(QuotaDate)

SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota
    , LEAD(SalesQuota, 1,0) OVER (PARTITION BY BusinessEntityID ORDER BY YEAR(QuotaDate)) AS NextQuota 
FROM @sales
--WHERE BusinessEntityID = 275

SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota
    , LAG(SalesQuota, 1,0) OVER (PARTITION BY BusinessEntityID ORDER BY YEAR(QuotaDate)) AS NextQuota 
FROM @sales
--WHERE BusinessEntityID = 275

How to use FIRST_VALUE() and LAST_VALUE() function

DECLARE @Test_table AS TABLE (
 [id] [int] IDENTITY(1,1) NOT NULL,
 [Department] [nchar](10) NOT NULL,
 [Code] [int] NOT NULL
)


--Insert some test data
insert into @Test_table values('A',111)
insert into @Test_table values('B',29)
insert into @Test_table values('A',11)
insert into @Test_table values('C',258)
insert into @Test_table values('D',333)
insert into @Test_table values('E',15)
insert into @Test_table values('F',449)
insert into @Test_table values('G',419)
insert into @Test_table values('H',555)
insert into @Test_table values('I',524)
insert into @Test_table values('J',698)
insert into @Test_table values('K',715)
insert into @Test_table values('L',799)
insert into @Test_table values('M',139)
insert into @Test_table values('N',219)
insert into @Test_table values('O',869)
insert into @Test_table values('P',767)

SELECT * FROM @Test_table


SELECT id,department,code,
FIRST_VALUE(code) OVER (ORDER BY code) FstValue,    ----// FIRST_VALUE  is 15 for all rows as it is value available on 1st rows
LAST_VALUE(code) OVER (ORDER BY code) LstValue    ---// LAST_VALUE returns last value from the row set
FROM @Test_table
ORDER BY id
OFFSET  0 ROWS
FETCH NEXT 5 ROWS ONLY


SELECT id,department,code,
FIRST_VALUE(code) OVER (ORDER BY code) FstValue,
LAST_VALUE(code) OVER (ORDER BY code ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) LstValue    ---// Max value
FROM @Test_table

---// After Insert one more department insert into @Test_table values('A',11)
----// Now The result set is divided into partitions based on the department, so the FIRST_VALUE is different but the same for each partition,
----// while the LAST_VALUE changes for the last row in that partition

SELECT id,department,code,
FIRST_VALUE(code)  OVER (PARTITION BY department ORDER BY code) FstValue,
LAST_VALUE(code) OVER (PARTITION BY department ORDER BY code) LstValue
FROM @Test_table
ORDER BY department

Tuesday, August 6, 2019

How to Set Up SQL Server Auditing


SQL Server auditing requires two objects: a server audit, and either a server or a database audit specification. It is best to have one server audit for the server audit specification, and a second audit that contains all of the database audit specifications for that server. This gives the DBA an extra level of control over auditing, since the DBA can deactivate all database auditing by deactivating the audit instead of all the individual specifications (Note: auditing will record the starting or stopping of auditing and who did it).

Prerequisites

As previously mentioned, SQL Server 2008 to SQL Server 2016 (before SP1) require Enterprise/Developer/Evaluation edition. Since we choose to write to the Security Log, we need to set some policies before installing auditing.
  • Setting Audit Policies on the server (A machine admin must perform these on the SQL Server)
    1. Open a command prompt with administrative permissions.
    2. Execute the following statement to enable auditing from SQL Server.
      auditpol /set /subcategory:"application generated" /success:enable /failure:enable
    3. Close the command prompt window.
         
  • Set Security Policy
    1. Open a run prompt (Windows Key + R)
    2. Type msc and then click OK. If the User Access Control dialog box appears, click Continue.
    3. In the Local Security Policy tool, expand Security Settings, expand Local Policies, and then click User Rights Assignment. You must be a machine admin on the server to do this.
    4. In the results pane, double-click Generate security audits.
    5. On the Local Security Setting tab, click Add User or Group.
    6. In the Select Users, Computers, or Groups dialog box, either type the name of the domain account on which SQL Server runs, and then click OK, or click Advanced and search for the account.
    7. Click OK.
    8. Close the Security Policy tool.
    9. Restart SQL Server to enable this setting.
There are additional procedures for SQL Server 2008. Jonathan Kehayias has written an excellent article hereto help you with prerequisites for that version of SQL Server. Since the 2008 version is getting pretty old, I figured that it would be better to leave the steps out of this article to save space.

Creating the Server Audit

The first thing we need to do in order to install SQL server auditing is to create an audit. The create Server audit T – SQL statement looks like this:
use [Master]
go
--Create Server Audit
CREATE SERVER AUDIT SAMPLE_server_audit
TO
    SECURITY_LOG;
go
--Enable Server Audit
ALTER SERVER AUDIT SAMPLE_server_audit WITH (STATE = ON);
Go
All of the options that are available for this statement are at this Microsoft link.

Server Audit Specifications

Once we have a server audit in place, we need to create a server audit specification. This audit will capture operations such as database creation and drops, the creation, alteration or drop of logins, DBCC statements and other events that affect the overall security of the server. The T SQL that we used to create a server audit specification looks like this:
-- Create Server Audit Specification
CREATE SERVER AUDIT SPECIFICATION SAMPLE_server_audit_spec
FOR SERVER AUDIT SAMPLE_server_audit
     ADD ( AUDIT_CHANGE_GROUP )
     ,ADD ( BACKUP_RESTORE_GROUP )
     ,ADD ( DATABASE_CHANGE_GROUP )
     ,ADD ( DATABASE_OWNERSHIP_CHANGE_GROUP )
     ,ADD ( BROKER_LOGIN_GROUP)
     ,ADD ( DBCC_GROUP )
     ,ADD ( LOGIN_CHANGE_PASSWORD_GROUP )
     ,ADD ( APPLICATION_ROLE_CHANGE_PASSWORD_GROUP )
     ,ADD (SERVER_PRINCIPAL_CHANGE_GROUP)
     ,ADD (DATABASE_PERMISSION_CHANGE_GROUP)
     ,ADD (DATABASE_ROLE_MEMBER_CHANGE_GROUP)
go
Individual options are grouped into "action groups." Microsoft has a write-up on this statement at this link. Microsoft also has a complete list of the action groups that you can capture, and what they get you at this link. What I specify above are a good but not overwhelming subset of events.

Database Audit Specifications

For each database that we wish to audit, a database audit specification, similar to the server Audit Specification, must be created. As with the server audit specification, the database audit specification is linked to a server Audit. A database audit specification can be used to track any DDL statement issued against the database. This gives you a record of who created, altered or dropped any object within the database.
Furthermore, you contract DML statements to a specific table or of a specific type. This can be very useful to track activity again sensitive tables. The T SQL to create a database audit specification looks like this:
use [master]
go
--Create the database Audit spec
CREATE DATABASE AUDIT SPECIFICATION [master_dbaudit]
FOR SERVER AUDIT [SAMPLE_server_dbaudit]
       ADD ( AUDIT_CHANGE_GROUP )
       ,ADD ( BACKUP_RESTORE_GROUP )
       ,ADD ( DATABASE_CHANGE_GROUP )
       ,ADD ( DATABASE_OBJECT_CHANGE_GROUP )
       ,ADD ( DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP )
       ,ADD ( DATABASE_OBJECT_PERMISSION_CHANGE_GROUP )
       ,ADD ( DATABASE_PRINCIPAL_CHANGE_GROUP )
       ,ADD ( DATABASE_ROLE_MEMBER_CHANGE_GROUP )
       ,ADD ( DBCC_GROUP )
       ,ADD ( SCHEMA_OBJECT_CHANGE_GROUP )
       ,ADD ( SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP )
       ,ADD ( DATABASE_ROLE_MEMBER_CHANGE_GROUP )
       ,ADD ( SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP )
       -- 2012-newer allowed events
       ,ADD ( DATABASE_LOGOUT_GROUP )
       ,ADD ( FAILED_DATABASE_AUTHENTICATION_GROUP )
       ,ADD ( USER_DEFINED_AUDIT_GROUP )
       ,ADD ( SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP )
WITH ( STATE = ON);
go
The action groups above are again a good example of what to use. We use a script that finds all databases on a server (except for model and tempdb) that don't have a database audit specification and uses those.
NOTE: There are several action groups that only arrived with SQL Server 2012. Our script notices if the server being audited is on 2008 and omits them.
The Microsoft documentation fully describing this statement is at this link. A complete listing of the action groups and what they track is given at this Microsoft link.

Understanding the Audit Output

First of all you need to know what to look for. All SQL server auditing events are stored with the event ID of 33205, making it extremely easy to filter away the millions of other security log entries that accumulate on any well configured server. Beware! Ensure that the systems administrator has increased the size of your security log to accumulate an appropriate number of entries so that auditing information is not lost. If you allow the logs to rollover, it is appropriate to consider some means of exporting the information to a text file for reference at a later date. If your server has HIPAA or SOX requirements it will be something that the auditors will ask you about. If you have the auditing, preserve the auditing!
Beware! SQL server audit log notes are big! The text associated with them can easily run over 1000 characters for a single event. Choosing an appropriate length of time to preserve event information will become extremely important as time goes on. Log forwarders such as Blanche usually charge by the number of bytes of data that they store. Archiving in perching becomes an issue.
Here's a look at a sample security log entry. I've blacked out private company information.
You can combine the Filter and Find features of the Event Viewer to search for specific things.

Utilizing the Audit

Picture this: The development team is hard at work on a critical project. All of a sudden the application crashed in the middle of a test. The report is that a stored procedure has gone missing. What happened? The developers pull out the problem resolution flowchart where every path ends at "Blame the Database and Call the DBAs." And you, the trusty DBA, are armed.
You sashay over to the Splunk console (or Event Viewer) and ask to search for events containing ID 33205 and the strings "Drop" and the procedure name. And you find out in under 30 seconds that Snidely Whiplash, a rookie developer, using workstation TieToTracks1, issued the drop from Management Studio. Even the time of the log entry precisely matches the failure. Root cause identified!
While young Mr. Snidely has some explaining to do, you and your boss breathe easy because DBA not only proved it had no responsibility for the problem, but rapidly aided developers in tracking down what happened.

Conclusion

This article is intended to be a primer to explain the power and basic implementation of SQL Server auditing. With a small amount of applied effort, you can install a worthwhile and effective tool to help you keep tabs on your servers and their databases.

Monday, August 5, 2019

Database Level Auditing with SQL Server 2014

--// First create server audit 
CREATE SERVER AUDIT [my_server_audit]
TO FILE
(
FILEPATH = N'E:\My Work\DBA'
,MAXSIZE = 10 MB
,MAX_ROLLOVER_FILES = 2147483647
,RESERVE_DISK_SPACE = OFF
)
WITH
(
QUEUE_DELAY = 1000
,ON_FAILURE = CONTINUE
)

ALTER SERVER AUDIT [my_server_audit] WITH (STATE = ON);
GO

--// NOW CREATE DATABASE AUDIT SPECIFICATION

USE Test_Data
GO
CREATE DATABASE AUDIT SPECIFICATION [my_dbaudit]
FOR SERVER AUDIT [my_server_audit]
ADD ( SCHEMA_OBJECT_ACCESS_GROUP )
,ADD ( SCHEMA_OBJECT_CHANGE_GROUP )
,ADD ( DATABASE_PERMISSION_CHANGE_GROUP )
,ADD ( DATABASE_OBJECT_PERMISSION_CHANGE_GROUP )
,ADD ( SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP )
WITH ( STATE = ON);

--// To check the audit file result after executing some queries on the query analyser 

CREATE TABLE employee
(
    id INT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    gender VARCHAR(50) NOT NULL,
    salary INT NOT NULL,
    department VARCHAR(50) NOT NULL
 )
INSERT INTO employee 
VALUES (1, 'Mark', 'Male', 9000, 'Sales')

SELECT * FROM employee

SELECT * FROM sys.fn_get_audit_file
(
'E:\My Work\DBA\*.sqlaudit', DEFAULT, DEFAULT
)
GO

----// To Disable/Enbable the server audit and database audit specification.

USE MASTER
GO
ALTER SERVER AUDIT [my_server_audit] WITH (STATE = OFF);
Go

USE Test_Data
GO
ALTER DATABASE AUDIT SPECIFICATION [my_dbaudit] WITH (STATE = OFF);

Go

Monday, July 29, 2019

Spatial SQL data types in SQL Server

Spatial data type

SQL server furnishes us with the geometry and geography SQL data types for conserving spatial data, which allows us to render graphical data. To be more specific, it is beneficial for creating, analyzing, comparing and retrieving spatial data.
This article will start with the definition of spatial data, with relevant examples. In addition, I’ll discuss the definition of spatial data types and detail elaboration of Spatial Data Objects and Draw spellbinding Objects. I will also explain, what the differences are between geometry and geography SQL Data Types.

What is spatial data?

Spatial data, also known as geospatial data, is a particular type of information about either the physical object or physical location of data that can be constituted by numerical values in geographic collaborate systems.
Generally, the use of spatial data is for representing the location, size, and shape of an object on planet Earth such as a mountain, lake, flat ground, township or so forth. On the top of that, spatial data may include attributes which can be given more information of the entity that is being represented.
Geographic Information Systems (GIS) or other specialized software applications should be appropriate to access, manipulate, visualize and dip analyze geospatial data.

Spatial SQL data types

There are two major supported data-type is SQL server namely geometry data type and geography data type.
  1. Geometry spatial data type
    It is substantially a two-dimensional rendering of an object and also useful in case of represented as points on a planar, or flat-earth data. A good example of it is (10, 2) where the first number ‘10’ identifies that point’s position on the horizontal (x) axis and the number ‘2’ represents the point’s position on the vertical axis (y).
    A common use case of the Geometry type is for a three-dimensional object, such as a building
  2. Geography spatial data types
    These are represented as latitudinal and longitudinal degrees, as on a round-earth coordinate system.
    The common use case of the Geography type is to store an application’s GPS data.
    In SQL Server, both SQL data types have been implemented in the .NET common language runtime (CLR)

Spatial data objects

This combines both special data types (geometry and geography). It supports a total of sixteen SQL data types in which eleven can be utilized in the database. To be more specific, these objects have inherited a particular property from their parent’s data types and this unique property distributes them as the object. Take the examples of a Polygon or point or CircularString.
Among them, ten of the depicted data objects will available to Geometry and Geography data types. The ten objects are respectively Point, MultiPoint, MultiLineString, CircularString, LineString, MultiLineString, CompoundCurve, Polygon, MultiPolygon, CurvePolygon, and GeometryCollection. However, the FullGlobe is utilized exclusively for the Geography SQL data types.
Spatial data types divided into two groups:
  1. Single geometries: It can be stored in the database only in one way
  2. A geometry collection: As the name suggests, is a collection of types of data objects
The object types associated with a spatial data type form a relationship with each other. In the following diagram, consider it as an example of how the object types of the Geometry SQL data types are related to each other. To be more specific, the graphic depicts the geometry hierarchy in which the geometry and geography data types are included. Dark grey is representing types of geometry and geography.
SQL Data Types
Using a specific example, if you define a point explicitly it uses the STPointFromText() method, STPointFromText ( ‘point_tagged_text’ , SRID )
The following example is for creating a geometry instance.
SQL Server return type: geography
If you define the same instance using the STGeomFromText() method,
SQL Server return type: geometry
So, both the geometry and geography SQL data types recognize the instance as a point.
Now let start drawing some objects …

Creating an absorbing object

  1. Square
    To start, we will attempt to draw a simple object, in this case a square. A square is a regular quadrilateral with 4 lines, in which it has four equal angles with four sides. We should be able to easily draw a square. Let’s take a look at the example, below
    geography SQL data types
  2. Circle
    A circle is a line enclosed, end to end, in which distance from any given point to another is constant. As we all know, the distance between any of the points is commonly called as the radius. For such and object we have to use a CircularString, which is the collection of circular arc segments. The curved segment is a circular arc segment which is defined by three points in a two-dimensional plane, where the first and third point can not be same.
    What happens when all three points of a circular arc are collinear is that the arc is the same as a line segment.
    Drawing a circle in geographical coordinates is a crucial task. Let’s review how to do it with the code below
    geography SQL data types
  3. Triangle
    A triangle is a polygon with three vertices and three edges. It is a very rudimentary shape in geometry. Check out the below code for it
    /wp-content/uploads/2018/07/word-image-70.png
  4. Filled Square
    Now, let’s start with some interesting objects!
    If you want to draw a solid square, in lieu of just edge, then a polygon come to mind. In the above example, we have just sketched a line in the object, but now a polygon holds everything within a line you draw
    /wp-content/uploads/2018/07/word-image-71.png
  5. Layer
    To dig a bit deeper, I will now pull a single object from some other objects.
    It is a very common scenario that we would need to draw two objects separately, but here I would like to combine two objects and add some interesting effects. The below query will evaluate a couple of objects, a square and triangle, however, both objects overlap and give a unique image, although they are independent in shape
    /wp-content/uploads/2018/07/word-image-72.png
  6. Layer Union
    Now it’s time to merge objects!
    When we execute the below query it will come up with the joining of two object layers with the method of STUnion and give a very distinct look. It looks like a triangle and square have merged into a single large image to generate a distinct object
    geography SQL data types examples
  7. Layer Intersection
    An intersect returns the portion of the object that is in common between two objects
    If the portion of the object exists in one query and not in other, it will be removed from the results. So the part that overlaps from object1 to object 2 is returned by the method STIntersection
    Layer Intersection in SQL data types
  8. Overlap
    STSymDifference finds which part of a group of objects is overlapped. The below query provides the difference between two objects
    /wp-content/uploads/2018/07/word-image-75.png
  9. Center
    Finally, if you want to find the center point of the object there are two ways. First you can calculate yourself and the other exciting way is use the method STCentroid. There is a buffer; named STBuffer, which adds the radial to the target. In short, by providing a buffer in the center, it is visible; but it’s just for purposes of visualization and it is not required for the following query work
    STCentroid in SQL Data Types

Differences between the geometry and geography SQL data types

How are the geometry and geography SQL Data Types Different? These two data types mostly work similarly however, they have a few key differences, especially while storing and manipulating data.

Connecting edges

Polygon and Line String data types are defined as only vertices. To be more specific, there is a straight line between a couple of vertical geometry types. However, there should be a little elliptic arc between two vertices in the geography type.

Circular arc segments

With the geometry datatype, the circular arc is defined as XY Cartesian coordinate plane in which z values are ignored. On the flipside, with Geography types, it is defined as curve segments on a reference sphere.

Measurements

In the geometry SQL data types, especially in the flat-earth system or planner, the area and measurement of distance are given in the coordinates the same unit of measurement. On the other hand, in the geography, round-earth system or ellipsoidal datatypes, the coordinates are given in degrees of latitude and longitude. Meters are the most common units of measurement.

Conclusion

To summarize, as per my understanding, I would say that for planar spatial data that is on a flat surface, the GEOMETRY SQL data type is the best option. However for the curved surface of the earth, which is terrestrial spatial data, objects can be more easily drawn using the GEOGRAPHY SQL data type.

References