SQL Journey

  • Your Email ID:

    Join 6 other followers

  • Top Rated

  • Bookmarks

  • Twitter Updates

  • Blog Stats

    • 16,734 hits
  • SocialVibe


Archive for the ‘Database Development’ Category

SQL Server: SET vs SELECT in Variable Assignment

Posted by Prashant on July 14, 2010

Most often we are using SET and SELECT interchangeably while assigning values to variable, however there are differences between them. In this post we will discuss some diff between SET and SELECT.

  • SET can assign value to only one variable at a time, where as SELECT can assign values to multiple variables at once.

Example

--Declare variable
DECLARE @myVar1 INT, @myVar2 VARCHAR(10);

--Assign value to variable using SET
SET @myVar1 = 1234;
SET @myVar2 = 'SQL Journey';

--Extract varible values
SELECT @myVar1, @myVar2

--Assign value to variable using SELECT
SELECT @myVar1 = 1234, @myVar2 = 'SQL Journey';

--Extract varible values
SELECT @myVar1, @myVar2
  • SET operation will raise an error if when result of a query returning multiple values is used to assign value to a variable. However  SELECT will not raise any error and assign the last record of query result to the variable. So, Microsoft recommends SET for variable assignment

Example:

CREATE TABLE #TestVar(myID int, myComments VARCHAR(30))
INSERT INTO #TestVar VALUES(1, 'A'),(2, 'B'),(3, 'C'),(4, 'D'),(4, 'E')

--Using SET
--Declare variable
DECLARE @myVar3 VARCHAR(30);
--Assign query result (returning multiple values) to variable
SET @myVar3 = (SELECT myComments FROM #TestVar WHERE myID = 6)
--Extract varible values
SELECT @myVar3

/****Result
Msg 512, Level 16, State 1, Line 8
Subquery returned more than 1 value.
This is not permitted when the subquery follows =, !=, <, <= , >, >= or
when the subquery is used as an expression.
****/

--Using SELECT
--Declare variable
DECLARE @myVar4 VARCHAR(30);
--Assign query result (returning multiple values) to variable
SELECT @myVar4 = myComments FROM #TestVar WHERE myID = 4;
--Extract varible values
SELECT @myVar4;
  • In the above case if the query result will not return any values then the variable value will be NULL either using SELECT or SET.
  • While talking in terms of performance variable assignment using SET will take less time as compared to SELECT.

Posted in Database Development, Interview Questions, SET vs SELECT, SQL Server | Tagged: , , , , , , | Leave a Comment »

SQL Server: Remove Non-Alphanumeric Characters from a Column

Posted by Prashant on July 13, 2010

In database we often need to clean the non-alphanumeric characters in some column of a table. Here is the code I use to remove non-alphanumeric characters in Sql Server.

Create the table with sample data:

   1: CREATE TABLE STRSTORE(COMMENT VARCHAR(2000))

   2:  

   3:  

   4: INSERT INTO STRSTORE(COMMENT) VALUES

   5: ('1.We^lcom&<e> to Sql{Journey}.&'),

   6: ('2=http://sqljourney.wordpress.com/'),

   7: ('3#[S$tring] &Cle<@anUp'),

   8: ('4-We* are'' do+ne~')

 

Remove non-alphanumeric characters from the column.

   1: WHILE @@ROWCOUNT > 1

   2:     UPDATE STRSTORE

   3:     SET COMMENT = REPLACE(COMMENT, SUBSTRING(COMMENT, PATINDEX('%[^a-zA-Z0-9 ]%', COMMENT), 1), '')

   4:     WHERE PATINDEX('%[^a-zA-Z0-9 ]%', COMMENT) <> 0

   5:  

   6:  

   7: SELECT * FROM STRSTORE

 

Let me also know if you have some better ideas.

Posted in Database Development, Interview Questions, SQL Server | Tagged: , , , , , , , , , | Leave a Comment »

SQL Server: Keyboard Shortcuts – Part 1

Posted by Prashant on July 8, 2010

Writing clean code is an important part in development activity. People sometimes ignore this may be because of some or other reason, which creates difficult to understand the code in later stage when it need changes. Here are some quick keyboard shortcuts for SQL Server Management Studio, which helps to write clean code and speed up development works.

So the below shortcuts related to code editing and execution in SSMS.

Purpose Keyboard Shortcut
Open New Query Window CTRL + N
Comment selected text CTRL + K then CTRL + C
Make selected text to UPPER case CTRL + SHIFT + U
Make selected text to LOWER case CTRL + SHIFT + L
Display estimated execution plan CRTL + L
Execute query F5 (Or) ALT + X (Or) CTRL + E
Show / hide result pane CTRL + R
Toggle between Query & Result pane F6

 

So have quick and clean coding…

Posted in Database Development, Interview Questions, Keyboard Shortcuts, SQL Server | Tagged: , , , | 1 Comment »

Fixing Error Message 1807 could not obtain exclusive lock on database ‘model’ in SQL Server

Posted by Prashant on June 15, 2010

Some days back I got this question from one of my friend, when he was trying to create a New Database, he is getting the below error message.

Msg 1807, Level 16, State 3, Line 1
Could not obtain exclusive lock on database ‘model’. Retry the operation later.
Msg 1802, Level 16, State 4, Line 1
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

The Situation:

He was trying to create table on Model database first then he tried to create a New Database. As Model database is used as a template for a database being created, SQL Server tries to obtain an Exclusive Lock on Model database. So if one session is using model database SQL Server can’t obtain exclusive lock on model.

If you are using SQL Server Management Studio try these steps:

Step1: Open a New Query (say SQL Query1.sql) and select “model” from database dropdown box.

Step2: Now in another Query (say SQL Query2.sql) run the below query:

select * from sys.dm_tran_locks

Observation: You will find result like below.

(Click on the image to enlarge)

This indicates Shared Lock has been Granted on resource_database_id = 3 (database_id: 3 is for model)

Step3: Now try to create database either from Object Explorer of SQL Server Management Studio or by CREATE DATABASE statement.

Step4: This time run query in step-3 and observe the result.

(Click on the image to enlarge)

This indicates an Exclusive lock on model database but has not been granted yet (it’s in WAIT state).

Solution:

Make sure to disconnect all the sessions which uses model database then CREATE DATABASE statement later. If this problem still remains, restart management studio and try again.

This is tested in SQL Server 2008, also leave your suggestions.

Posted in Create Database, Database Development, Lock, SQL Server, SQL Server Error | Tagged: , , , , | 1 Comment »

Insert or Copy Data into Table

Posted by Prashant on June 11, 2010

This post is for a common situation most of us face while working with a database, which is copy/insert to a table.  We can use INSERT & SELECT to copy data into a database table in three ways.

  • INSERT Statement (Direct insert data values into the table):

Using INSERT statement we can add one data row at a time to destination table.

--Example: 1
CREATE TABLE Table01
(Column1 INT PRIMARY KEY, Column2 varchar(10))
GO

INSERT INTO Table01(Column1,Column2) VALUES(101,'A')
INSERT INTO Table01(Column1,Column2) VALUES(102,'B')
INSERT INTO Table01(Column1,Column2) VALUES(103,'C')
INSERT INTO Table01(Column1) VALUES(104)
GO

SELECT Column1,Column2 FROM Table01
GO
  • INSERT Statement with a SELECT Sub-Query:

If the destination table (we want to populate) is already created in the database, then using INSERT statement with a SELECT sub-query, we can copy data rows from one table to another.  The number of columns listed in INSERT statement must be same as the columns listed in SELECT statement and their data types must match.

--Example: 2
CREATE TABLE Table02
(Column1 INT IDENTITY, Column2 VARCHAR(10),
Column3 VARCHAR(8) DEFAULT('Welcome1'))
GO

INSERT INTO Table02(Column2)
SELECT Column2 FROM Table01
GO

SELECT Column1, Column2,Column3 FROM Table02
GO
  • SELECT with INTO Statement:

If the destination table (we want to populate) is not available in the database, then using SELECT INTO statement also it will create the table on the fly and copy data to it from the source table.

--Example: 3
SELECT Column1, Column2, Column3
INTO NewTable
FROM Table02
WHERE Column2 IS NOT NULL
GO

SELECT * FROM NewTable
GO

Please let me know your valuable comments.

Posted in Data Types, Database Development, General, Identity Column, Interview Questions, SQL Server | Tagged: , , , , , | Leave a Comment »

Condition based Update in SQL Server

Posted by Prashant on June 9, 2010

In SQL Server conditional update can be done using CASE.

--Update employee monthly commission based on their rating
UPDATE Employees
SET Comm =
CASE
WHEN (Rating between 2 and 3)THEN (Salary * 0.1)
WHEN (Rating between 3.1 and 4)THEN (Salary * 0.15)
WHEN (Rating between 4.1 and 5)THEN (Salary * 0.25)
ELSE 0.0
END

This example is just to demonstrate a scenario. Here it examines the employee rating to determine what should be the updated Commission. The CASE expression uses range of employee rating to update the commission amount.

Posted in Database Development, General, Interview Questions | Tagged: , , , , | Leave a Comment »

Check existence of Table or Database before creating it in SQL Server

Posted by Prashant on June 9, 2010

To check if a table is exists or not a database:

--Check if table exists
IF EXISTS (SELECT 1 FROM sys.tables WHERE name = 'TableName')
PRINT 'TableName available.'
ELSE
PRINT 'TableName not available.'

Similar way we can also check if a database is exists or not before creating.

--Check if database exists
IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'DBName')
PRINT 'DBName available.'
ELSE
PRINT 'DBName not available.'

Please leave your valuable comments on this.

Posted in Database Development, General, SQL Server | Tagged: , , , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.