SQL Server security best practice

Security! This is the word comes in mind of every concerned person when it come...

Change the Collation Settings in MS SQL Server

This post will show you how to change the collation settings in MS SQL Server for specific database...

Resolve collation conflict

In this post I will show you how you can resolve collation conflict error...

Book: SQL Server 2008 High Availability

In this book I have tried to cover every single piece of information that might requires for installing and configuring SQL Server HA option like Clustering, Replication, Log Shipping and Database Mirroring...

Why to recompile Stored Procedure

Generally, we create views and stored procedures (proc here after) ...

Showing posts with label MS Sql server. Show all posts
Showing posts with label MS Sql server. Show all posts

3/28/2012

SQL Server # Storing Hierarchical Data – Parent Child n’th level # TSQL

Introduction

Today, I would like to explain one way in which we can store the HIERARCHICAL data in SQL tables. A general table structure which people come up to store this kind of data is -

1

Where, EmployeeID id the UniqueID alloted to every new employee record inserted into the table and ManagerID is the EmployeeID of the immediate manager of the employee. Keeping in mind that Manager is also an employee.

Problem Statement

This table structure very well serves the purpose as long as we have 1-Level hierarchy. However, if the hierarchy is of n'th level, the SELECT statement to fetch the records becomes more complex with this kind of table structure. Suppose, we want to fetch the complete TREE of a particular employee, i.e. list of all the employees who are directly or indirectly managed by a particular employee. How to do it……..?

Thanks to CTE’s for making the life a bit easier – as using them in a recursive manner, we can get the work done. Please follow this msdn link to see an implementation using recursive CTE.

Suggested Table Structure

2

Here, I have just included a new column [PATH]. It is of VARCHAR(MAX) type. I have taken it as VARCHAR(MAX) just to make sure the field is long enough to store the complete path. But one can assign appropriate size as per their system’s requirement.

The basic idea of the [path] column is to store the complete hierarchical path of any employee separated by a delimiter as under -

3

Calculating the new path is very simple. It’s just, {New Path} = {Parent Path} + {Self ID} + {Delimiter}

Now, suppose if I want to fetch all the employees who are directly or indirectly working under EmployeeID = 2, I can use the below tsql -

;WITH CTE AS (
SELECT 1 EmployeeID,NULL ManagerID, '\1\' [Path]
UNION ALL    
SELECT 2 EmployeeID,1 ManagerID, '\1\2\' [Path]
UNION ALL    
SELECT 3 EmployeeID,1 ManagerID, '\1\3\' [Path]
UNION ALL    
SELECT 4 EmployeeID,2 ManagerID, '\1\2\4\' [Path]
UNION ALL    
SELECT 5 EmployeeID,4 ManagerID, '\1\2\4\5\' [Path]
)
SELECT
  *
FROM
  CTE
WHERE
  [Path] LIKE '%\2\%'

We can use a simple logic to even find out the level of the Employee -


SELECT
  *,
  (LEN([Path]) - LEN(REPLACE([Path],'\',''))) - 2 [Level]
FROM
  CTE
WHERE
  [Path] LIKE '%\2\%'

4

2 is subtracted from the formula as the length of delimiter for Level-0 is 2.

Conclusion

Hope, this simple trick could save a lot of time for the ones who find themselves lost playing with the hierarchical data.

1/31/2011

Tip for Backing up User Databases

We all take a database backup as a first resort to recover from a damage occur during the disaster / server crash / for any other reason if require to recover or restore our data back to its previous stat as it was before the database server was crashed!! And for this we schedule a job or make use of database maintenance plan which will take a database backup be it Full / Differential or Log, and we all take a special care and consideration when we design the backup strategy!!

But what happened if one fine day when you need your database backup file to work well and it doesn’t!! What if it is corrupted!! And you have only a Full backup for that day?

Today I am going to discuss about the script that I have posted in the download section couple of days back; the script will not only perform a full database backup of all user databases but it will also verify the validation of the backup file!  It's a must to have a database backup strategy where in we do not keep multiple copies of database backup  and if one have one or two days retention policy. 

declare @int int ,@dbname varchar(22),@maxdbid int
declare @int int ,@dbname varchar(22),@maxdbid int
declare @bkpath varchar(25),@path varchar(50)
select @maxdbid= max(dbid) from master..sysdatabases
set @int = 0
set @bkpath='C:\SQLDB\backup\'
USE master
while (@int < @maxdbid)
begin
set @dbname = (select [name] from master..sysdatabases where dbid=@int and status!=1073807392)  
if (@dbname != 'tempdb') 
 begin
  select @int as 'DBID',@dbname as 'Database'  
  select @path=@bkpath+@dbname+CONVERT(VARCHAR(12),GETDATE(),112)
  BACKUP DATABASE @dbname TO DISK = @path  
  print @path
  print @bkpath
  restore verifyonly from disk=@path
  end  
 set @int = @int + 1  
 continue 
 break
end

Check the line # 17, restore verifyonly from disk = @path is the line that will help us to overcome above issue. This is not a hidden code lying in a secret place somewhere but this is something that we may have missed in our code – I know most of you have already using this option for your database backup validation, how many of you are using this option? Or out of curiosity any other option!!

PS: This code is the very basic code that I have wrote initially, you may modify and use the script according to your requirement without any obligation.
Your suggestions welcome!

Regards
- Hemantgiri S. Goswami

3/30/2009

TechNet Webcast: SQL Server 2008 Capabilities for Meeting PCI Compliance Needs

There will be a web cast on SQL Server 2008 Capabilities for Meeting PCI Compliance Needs at 1 PM Pacific Time, get register

http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032404173&EventCategory=4&culture=en-US&CountryCode=US

3/09/2009

Community launched | Surat SQL Server User Group | DotNetChaps

Hi,

We have formed a Technical Community User Group. The aim of this User Group is to share/exchange what all we have in terms of the knowledge.

We have two separate forums for MS SQL and for Dot Net technology to avoid confusion. You may post all your queries pertaining to MS SQL at http://www.surat-user-group.org and if you are having a query in .Net (be it asp .net, c# or vb .net) please post it to http://tech.groups.yahoo.com/group/DotNetChaps/

http://www.surat-user-group.org is having an association with SQLPASS (http://www.sqlpass.org) and is an official SQLPASS Chapter.

http://tech.groups.yahoo.com/group/DotNetChaps/ is having an association with iNETA.

1/19/2009

Microsoft Virtual Techdays

It would be a good time again.... Microsoft Virtual Techday (VTD) is back; below is an agenda
http://www.virtualtechdays.com/agendaday1.aspx

Get registered!!

1/11/2008

SQL Server 2008 - download November CTP now!!!

SQL Server 2008 November CTP is available for download, click here to grab your copy of SQL Server 2008

Here are some more resources on SQL Server 2008

SQL Server 20008 Product Overview

SQL Server 2008 Videos

SQL Server 2008 White Papers

SQL Server 2008 Webcasts

Happy Learning all :-)

11/12/2007

Learn SQL Server 2008 from Microsoft

Since some times their is a discussion on what's new in SQL Server 2008, when the reference material will be available!! Here is an answer to this, Microsoft has introduce a course at its E-Learning, the course aims to educate IT Professional who has prior experience working with SQL Server. Microsoft has made learning SQL Server 2008 easy by offering e-learning course, the course is devided into three category:

Enterprise Data Plateform

Business Intellegence

Database Developement

more details on this course is available here, all you need to have is a Windows Live Account https://www.microsoftelearning.com/eLearning/offerDetail.aspx?offerPriceId=139087

10/26/2007

Some Tips for Merge Replication

* SQLAgent service should run under same domain account, which has local admin privilege and “Log in as a service” permission. This requires on both the server. In case, if SQL Server is not part of any Domain. We can use the user account which has identical name and password at servers i.e. ReplUser on SRVA with password ReplUser! and identically ReplUser on SRVB with password ReplUser!
* User account that is used to run the SQLAgent services have to have sysadmin privilege on both server, and it should be added in to db_owner fixed db role for database which is being replicated/replicating.
* Should include all the tables which are referenced, this will help to keep data consistency.
* If there are text/image column we need to update those column explicitly Updatetext statement. http://msdn2.microsoft.com/en-us/library/aa260658(SQL.80).aspx
* Try to avoid using Identity column as PK but if it is already implemented modify the property of Identity column as ‘Not for Replication’.
* Define both server (Publisher and Subscriber) as remote server at each other.
* Allocate adequate space for distribution, subscription and publication db.
* Avoid using Identity column as PK but if it is already implemented modify the property of Identity column as ‘Not for Replication’.
* Rowguid column is must, which also can be added at the time of configuring Merge replication.
* sp_dropmergearticle can be used to drop article from publication.
* sp_addmergearticle can be used to add article to publication.
Below are some links that will be usefull for replication troubleshooting, they are:
Troubleshooting Merge Replication http://support.microsoft.com/kb/315521 and
Managing Identity values in Replication environment http://msdn2.microsoft.com/en-us/library/aa237098(SQL.80).aspx
Violation of Primary Key (PK) Constraint http://support.microsoft.com/kb/813494

Merge agent incorrectly deletes rows after PK violation error
Adding and Droping an article in existing publication http://msdn2.microsoft.com/en-us/library/ms152493.aspx
Working with BLOB data in Replciation http://technet.microsoft.com/en-us/library/ms151206.aspx

10/05/2007

Estimating the size of Table

Many time it happens we were wrong with the Estimation of Table Size, wrong estimation of Row Size can trouble us with the growth of the database and ultimately we are ending up with the space crunch, and all this because of wrong Estimation of Table Size. So what we should consider the most with Estimating Table Sizing!!! Nullbitmap is the most important criteria here to take into consideration whenever you do a Estimation of Row Size, here is an excellent article on Row Size Estimation http://msdn2.microsoft.com/en-us/library/aa933068(SQL.80).aspx and http://msdn.microsoft.com/en-us/library/ms175991.aspx

9/27/2007

Tuning Stored Procedure

Most of the time I come accross the thread wherein user has requested to get started with stored procedure performance tuning , so here are some good reference material for tuning stored procedure and optimize stored procedure for performance
http://www.sql-server-performance.com/tips/stored_procedures_p1.aspx, http://www.sqlservercentral.com/articles/Performance+Tuning+and+Scaling/performancetuningstoredprocedures/2505/ and http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1247499,00.html

9/10/2007

Automate Profiler Trace

The question I recently come accorss on SQL Server Performance, the OP was asking on "How to automate profiler trace" , their are system stroed procedure that can be used to automate profiler trace. The system stored procedure you can use are sp_trace_create,sp_trace_generateevent,sp_trace_setevent,sp_trace_setfilter and sp_trace_setstatus. Here is complete procedure described on "How to automate profiler trace" , refer http://vyaskn.tripod.com/server_side_tracing_in_sql_server.htm

Here is a link on "How to monitor trace on SQL Server 2005" http://support.microsoft.com/kb/912914/en-us

9/06/2007

New KB articles are added for SQL Server 2005

New Knowledge Base articles are added for SQL Server 2005, Here are the links

FIX: The performance of a query that performs an insert operation or an update operation is much slower in SQL Server 2005 SP2 than in earlier versions of SQL Server 2005

FIX: You receive an incorrect result when you use a SQL Native Client provider to read the data on the client computer in SQL Server 2005

How to enable the SQL Server 2005 Integration Services process to generate a dump file when the process experiences exceptions

FIX: Error message when you run a query that selects many columns and that joins many tables in SQL Server 2005 Service Pack 2: "The query processor could not produce a query plan"

FIX: An application that is included in SQL Server 2005 may stop responding when you specify a network protocol that is not valid in the application

FIX: Error message when you use Database Engine Tuning Advisor to tune a database in SQL Server 2005 Service Pack 2: "An unhandled win32 exception occurred in dtaengine90.exe [4308]"


FIX: Error message when you use the Bcp.exe utility together with the queryout option in Microsoft SQL Server 2005: “BCP host-files must contain at least one column”

Some or all SQL Server 2005 services are not listed in SQL Server Configuration Manager, or you receive a "No SQL Server 2005 components were found" error message when you perform operations in SQL Server 2005 Surface Area Configuration

Error message when you run a distributed query against a loopback linked server in SQL Server 2005: "Transaction context in use by another session" or "MS DTC has cancelled the distributed transaction"

You cannot upgrade the named instance of SQL Server 2000 Desktop Engine Service Pack 3a that is installed together with Application Center 2000 Service Pack 2 to SQL Server 2000 SP4

Renaming SQL Server that hosts Reporting Server

Sometimes business demands or change in naming convention for servers lead to situation where one should change / rename the Server running MS SQL Server, it would not that panic renaming SQL Server as you have sp_dropserver and sp_addserver to help you, but what if this SQL Server box have reporting server too; well microsoft has workaround for it refer - http://technet.microsoft.com/en-us/library/ms345235.aspx

7/16/2007

Disaster Recovery Articles on MS SQL Server

Here are some good Disaster Recovery articles on MS SQL Server
http://support.microsoft.com/kb/307775