:::: MENU ::::

Posts Categorized / T-SQL Scripts

  • Oct 14 / 2008
  • 0
dbDigger, T-SQL Scripts, T-SQL Tips and Tricks

Basic T-SQL Refresher for preliminary learners

During the early days when i planned to permanently enter into Database Administration field, i searched a lot of preliminary books and code snippets. As T-SQL is core of SQL Server DBA, i spend most of time to cover the concepts and to gain as much skill as possible. During that time i prepared some code refreshers that i usually consulted later for practice of T-SQL. So primarily following code and explanation is for beginners and field switchers those want to strat careers in Database Administration. Most of concepts here will be helpful in iinterview questions and day to day T-SQL paradigm. I will try to update this post later also when required.
Code used here is run under pubs database and is compatible to SQL Server 2000 and SQL Server 2005.

 
Select 'Wellcome to T-SQL'  

 

Concatenation and alias
Concatenation is done using ‘+’. Alias is also used in two ways. Alias can be used in ‘select’ and ‘from’ statement

 
USE pubs  
 GO  
 SELECT au_fname+au_lname fullName, [STATE]+','+zip AS location  
 FROM authors auth  

Here in above script concatenation is used in select list. Alias is used in select list (fullname) and in from clause (auth)

 

Comparison on string data
Comparison operators can also be used with text/string data

 
SELECT [STATE]  
 FROM authors  
 WHERE [STATE] > 'ma'  

Above script will compare the given strings according to alphabetical order. It will return states that start with alphabets after ma.

 

IN operator
IN operator may be used instead of multiple OR

 
SELECT au_fname,au_lname, [STATE]  
 FROM authors  
 WHERE STATE IN ('TN','OR','MI','MD')  

 

Between Operator
Between operator may be used instead of > and <>

SELECT price  
 FROM titles  
 WHERE price BETWEEN 10 AND 20  

 

Wild cards
T-SQL uses two wild cards
‘%’ is used multiple match and ‘_’ is used for single char match

 
SELECT au_fname, au_lname  
 FROM authors  
 WHERE au_fname LIKE 'Abr%'  

Above script will look for names with Abr as first three characters and any characters after these three chars.

 
SELECT au_fname, au_lname  
 FROM authors  
 WHERE au_fname LIKE 'Ab_aham'  

Above script will look for names starting with Ab and ending with aham, and any character there in place of _.

 

Escape character
If we have to find % inside data, then use escape character. Normally @ is used

 
SELECT notes  
 FROM titles  
 WHERE notes LIKE '%@%%' ESCAPE '@'  

 

Pattern matching
Pattern matching may be used when we have a number of expected variations for search

 
SELECT au_lname, au_fname  
 FROM authors  
 WHERE au_fname LIKE '[l,m,s]%'  

Suppose we want to retrieve four letter name whose first char is capital and other are small

 
SELECT au_lname, au_fname  
 FROM authors  
 WHERE au_lname LIKE '[A-Z][a-z][a-z][a-z]'  

Suppose in a case sensitive column we want to retrieve book with title
“life without fear”, but do not know that without is capital or small

 
SELECT title_id, title  
 FROM titles  
 WHERE title LIKE '%[Ww][Ii][Tt][Hh][Oo][Uu][Tt]%'  

We want to retreive just those authors whose first name is 4 char long

 
SELECT au_fname  
 FROM authors  
 WHERE au_fname LIKE '____'  

We can use negate by using <>, !=, ^, not

 
SELECT au_fname  
 FROM authors  
 WHERE au_fname LIKE '[^][^][^][^]'  

You have a column that accepts just 6 chars while inserting data you have to be careful for signs and digits use ‘[A-z][A-z][A-z][A-z][A-z][A-z]’

 

Order by
Order by may be used with column names or numbers. Also we may use calculations for order criteria. Nulls will be placed at start or end of list as spcified by DBMS

 
SELECT au_fname+au_lname name  
 FROM authors  
 ORDER BY name  

 

Distinct
Distinct is used just after select key word. Only one distinct may be there per SQL statement. Will be applied to all columns in select list
Distinct performs like group by except it does not sort the data

 
SELECT DISTINCT [TYPE]  
 FROM titles  

 

group by
Group by works same as distinct. True power comes with aggregate functions like count(). An aggregate can not be specified in group by clause. when using group with aggregate, u have to specify all non aggregate. clolumns in group by clause

 
SELECT [STATE], COUNT(*)  
 FROM authors  
 GROUP BY [STATE]  

 

Having

  • Having clause works like where with a fundamental difference.
  • Where clause defines set of data on which grouping is perfomed.
  • Having clause defines which groups are going to be return to user. Having clause generally contains aggregates as part of selection criteria

 

Compute and compute by
Compute is used to generate summary data. It is backword compatibility. Analysis services roll up is advance to it. Following restrictions are applied.

  • U can use columns in select list only.
  • U must order by compute by column.
  • U can use any aggregate function except count(*).
  • Columns listed after compute by should be identical to those ordered in select clause
  • Oct 06 / 2008
  • 0
dbDigger, Monitoring and Analysis, Security and Permissions, T-SQL Scripts

Get list of all possibble permissions for a SQL Server 2005 object

It is interesting question that how to get all the possible permissions for SQL Server 2005 object. The object may be any table, view, function. Apart from these objects you could even get list of all possible permissions for your database or server.
Format for this T-SQL script is

 
USE DBNameHere  
 GO  
 SELECT *  
 FROM fn_my_permissions('ObjectName', 'type');  
 GO  

In above script provide DB name first. If you want to generate possible permissions for a database or server itself then provide NULL as objectname and write ‘database’ or ‘server’ as type parameter. For example to get possible server level permissions for server itself we will have following syntax

 
SELECT permission_name  
 FROM fn_my_permissions(null, 'server');  
 GO  

Similarly to get possible permissions for AdventureWorks database we have following syntax

 
USE AdventureWorks  
 GO  
 SELECT permission_name  
 FROM fn_my_permissions(null, 'database');  
 GO  

Here are some examples to get list of all possible permissions for SQL Server objects like view, table, database and server.
To get list of all possible permissions for a view [purchasing.object] in AdventureWorks database

 
USE AdventureWorks  
 GO  
 SELECT *  
 FROM fn_my_permissions('purchasing.vVendor', 'object');  
 GO  

Similarly to get list of all possible permissions for a table [production.product] in AdventureWorks database

 
USE AdventureWorks;  
 GO  
 SELECT *  
 FROM fn_my_permissions('production.product', 'object');  
 GO  

Above commands will provide you all permissions/privileges list. you may choose among these as required.

  • Oct 06 / 2008
  • 0
dbDigger, SQL Server Agent scheduled Jobs, System Stored Procedures, T-SQL Scripts

Create new SQL Agent logs archive files without restart in SQL Server 2005

Just like SQL Server Logs Files, SQL Agent logs archive files are also processed during restart of SQL Server agent. A new SQL Agent file is created and oldest one is replaced if maximum count is exceeded. In situations where production servers remain online with critical jobs scheduled, SQL Agent is not restarted for days and even months. So a way is required to process the SQL Agent logs files without restart. Following system stored procedure will do it for you in SQL Server 2005.

 
USE MSDB  
 GO  
 EXEC sp_cycle_agent_errorlog  
 GO  

As a result new logs archive file for SQL Agent logs will be created, just as it would be through restart of SQL agent Service.

  • Oct 06 / 2008
  • 0
dbDigger, System Stored Procedures, T-SQL Scripts, Transaction log files

Recycle SQL Server logs archives without restart

Every time SQL Server restarts, a new error log file is created. If file count is going to be increase the maximum count specified, then oldest file is replaced by new one else just a new file is added. This process helps to manage the size of logs file. But in situations where production servers remain online for days and months without any restart, the logs file may be heavily populated. This causes difficulty while loading the file with more log records for analysis.
So a mechanism is required to process the log files without SQL Server restart. Following system stored procedure will do it for you

USE MASTER  
 EXEC sp_cycle_errorlog  
 GO  

As a result a new logs file will be craeted and oldest will be replaced if maximum count is going to be exceed.

  • Sep 17 / 2008
  • 0
DBA best practices, DBA thoughts, dbDigger, Documentation, T-SQL Scripts

Naming cionventions for SQL Srever user objects

database objects Naming conventions

Following SQL Server objects naming conventions may be used primarily to standardize the DB objects naming structure. Conventions will be applied to Tables, Views, Stored Procedures, Functions and Triggers.

Tables

  • Table name should be descriptive of its content e.g staff, staff_education.
  • No space should be used; under score may be used where necessary.
  • Adding tbl as a prefix should be avoided.
  • Domain of functionally may be reflected in name as for Inventory Management System related tables, we may name as IMS_Wing, IMS_Vendor, IMS_Issue.

Views

  • View name should have VW as prefix. E.g vw_staff_posting, vw_sancstrength
  • View name may also contain names of its base table/tables. E.g vw_staff_staffeducation

Stored Procedure

  • Name of user stored procedure should be suffixed with USP.
  • Stored Procedure name should reflect application to which it belongs. For example for any AD Hoc reporting application we may use USP_AdHoc_GetSummary

User Defined Functions

  • Name of user defined function should have UDF as a prefix.
  • UDF name should reflect the application to which it belongs. For example for any AD Hoc reporting application we may use UDP_AdHoc_calculateSummary

Triggers

  • Trigger name should always have T as prefix.
  • Next to T it should have I, D or U to reflect insert, delete or update event on which it will be invoked. E.g TI_staffLog, TU_staffLog, TD_StaffLog.
Consult us to explore the Databases. Contact us