About Me
- Vikram Mahapatra (Viki)
- Mumbai, Maharastra, India
- He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari
Search This Blog
Wednesday, August 31, 2011
A tribute to the bosses!!!
Chai k Liye jaise Toast hota hai,
Waise har ek BOSS zaruri hota hai.
Koi friday evening review par bulaye
Koi saturday ko office bulaye
Ek teri idea ko apna bataye,
Aur Ek tera target har month badhaye
Koi nature se gentle,
koi bura hota hai,
Par har ek boss zaruri hota hai.
Ek ghadi ghadi review kare par kabhi kabhi advice de
Ek kabhi kabhi review kare aur ghadi ghadi advice de
Koi Gyan ka ghoomta phirta satellite,
Koi din raat rakhe team ko tight;
Koi welcomed hai, koi forced hota hai
Par har ek boss zaruri hota hai
Koi bossy boss,
koi friendly boss
Koi Data crazy excel boss.
Moody boss, koi gloomy boss
Early morning office aane wala Boss,
Koi late night jaane wala Boss
Koi promote na kare aur appraisal me tarsaye
Koi good suggestion ko bhi thukhraye
Koi best friend aur, koi aloof hota hai
Par har ek boss Zaruri hota hai !!
Post Reference: Vikram Aristocratic Elfin Share
Saturday, July 2, 2011
Lock up your transaction...
Lock types
There are three main types of locks that SQL Server 7.0/2000 uses:
· Shared locks
· Update locks
· Exclusive locks
Shared locks are used for operations that do not change or update data, such as a SELECT statement.
Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.
Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.
Shared locks are compatible with other Shared locks or Update locks.
Update locks are compatible with Shared locks only.
Exclusive locks are not compatible with other lock types.
Let me to describe it on the real example. There are four processes, which attempt to lock the same page of the same table. These processes start one after another, so Process1 is the first process, Process2 is the second process and so on.
Process1 : SELECT
Process2 : SELECT
Process3 : UPDATE
Process4 : SELECT
Process1 sets the Shared lock on the page, because there are no another locks on this page.
Process2 sets the Shared lock on the page, because Shared locks are compatible with other Shared locks.
Process3 wants to modify data and wants to set Exclusive lock, but it cannot make it before Process1 and Process2 will be finished, because Exclusive lock is not compatible with other lock types. So, Process3 sets Update lock.
Process4 cannot set Shared lock on the page before Process3 will be finished. So, there is no Lock starvation. Lock starvation occurs when read transactions can monopolize a table or page, forcing a write transaction to wait indefinitely. So, Process4 waits before Process3 will be finished.
After Process1 and Process2 were finished, Process3 transfer Update lock into Exclusive lock to modify data. After Process3 was finished, Process4 sets the Shared lock on the page to select data.
Shared locks are used for operations that do not change or update data, such as a SELECT statement.
Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.
Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.
Shared locks are compatible with other Shared locks or Update locks.
Update locks are compatible with Shared locks only.
Exclusive locks are not compatible with other lock types.
Let me to describe it on the real example. There are four processes, which attempt to lock the same page of the same table. These processes start one after another, so Process1 is the first process, Process2 is the second process and so on.
Process1 : SELECT
Process2 : SELECT
Process3 : UPDATE
Process4 : SELECT
Process1 sets the Shared lock on the page, because there are no another locks on this page.
Process2 sets the Shared lock on the page, because Shared locks are compatible with other Shared locks.
Process3 wants to modify data and wants to set Exclusive lock, but it cannot make it before Process1 and Process2 will be finished, because Exclusive lock is not compatible with other lock types. So, Process3 sets Update lock.
Process4 cannot set Shared lock on the page before Process3 will be finished. So, there is no Lock starvation. Lock starvation occurs when read transactions can monopolize a table or page, forcing a write transaction to wait indefinitely. So, Process4 waits before Process3 will be finished.
After Process1 and Process2 were finished, Process3 transfer Update lock into Exclusive lock to modify data. After Process3 was finished, Process4 sets the Shared lock on the page to select data.
Sunday, June 12, 2011
Fun with CURSOR, print all your SP
Use cursor to print all stored procedure in your database as a text. Use the code below to get all your SP in current database.
USE MyDatabase
GO
DECLARE @proc_Name VARCHAR(100)
DECLARE @mySP_cursor CURSOR FOR
SELECT s.name FROM sysobjects s WHERE type = 'P'
OPEN @mySP_cursor
FETCH NEXT FROM @mySP_cursor INTO @proc_Name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_HelpText @procName
FETCH NEXT FROM @mySP_cursor INTO @proc_Name
END
CLOSE @mySP_cursor
DEALLOCATE @mySP_cursor
GO
Happy coding... :)
Post Reference: Vikram Aristocratic Elfin Share
USE MyDatabase
GO
DECLARE @proc_Name VARCHAR(100)
DECLARE @mySP_cursor CURSOR FOR
SELECT s.name FROM sysobjects s WHERE type = 'P'
OPEN @mySP_cursor
FETCH NEXT FROM @mySP_cursor INTO @proc_Name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_HelpText @procName
FETCH NEXT FROM @mySP_cursor INTO @proc_Name
END
CLOSE @mySP_cursor
DEALLOCATE @mySP_cursor
GO
Happy coding... :)
Post Reference: Vikram Aristocratic Elfin Share
Surrogate Key, Candidate Key, Primary Key, Alternate Key and Composite Key
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.
A key formed by combining at least two or more columns is called composite key.
A key formed by combining at least two or more columns is called composite key.
Surrogate Key : Artificial key generated internally that has no real meaning outside the Db (e.g. a Unique Identifier or Int with Identity property set etc.). Implemented in SQL Sevrver by Primary Key Constraints on a column(s).
Post Reference: Vikram Aristocratic Elfin Share
Update Employee Table with MERGE
Once very good friend of mine asked me how to update an employee master table having fields
emp_id,
emp_name,
department_id, (refer to dept_id of Department_Master table)
department_name
where department_name fields is null and he want to update department_name with the correspondent department_id.
The solution is very simple i told him to do it by cursor or using temporary table and loop through the temp table.
But today when i was toying with MERGE i found one more solution to same question, i have yet not executed it but i m pretty confident it will work and it is the best solution to the above question
MERGE Employee_Master AS ed
USING (SELECT dept_id,dept_name FROM Department_Master) AS dm
ON dm.dept_id = em.dept_id
WHEN MATCHED THEN UPDATE SET em.dept_name = dm.dept_name;
Just try it n see the result.
Happy coding :)
Post Reference: Vikram Aristocratic Elfin Share
emp_id,
emp_name,
department_id, (refer to dept_id of Department_Master table)
department_name
where department_name fields is null and he want to update department_name with the correspondent department_id.
The solution is very simple i told him to do it by cursor or using temporary table and loop through the temp table.
But today when i was toying with MERGE i found one more solution to same question, i have yet not executed it but i m pretty confident it will work and it is the best solution to the above question
MERGE Employee_Master AS ed
USING (SELECT dept_id,dept_name FROM Department_Master) AS dm
ON dm.dept_id = em.dept_id
WHEN MATCHED THEN UPDATE SET em.dept_name = dm.dept_name;
Just try it n see the result.
Happy coding :)
Post Reference: Vikram Aristocratic Elfin Share
Fetch Excel Records using ADO.Net
This code snap will fetch each record from your excel sheet 1 located at D:\ drive and return records as datatable.
public static DataTable GetItemsFromExcel1()
{
DataTable dt = new DataTable();
oleDbConnection excelConnection =
new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;"
+ @"Data Source=D:\YourFile.xls;"
+ @"Extended Properties=""Excel
8.0;HDR=Yes;IMEX=1;""");
excelConnection.Open();
try
{
OleDbDataAdapter dbAdapter =
new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelConnection);
dbAdapter.Fill(dt);
}
finally
{
excelConnection.Close();
}
return dt;
}
Post Reference: Vikram Aristocratic Elfin Share
public static DataTable GetItemsFromExcel1()
{
DataTable dt = new DataTable();
oleDbConnection excelConnection =
new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;"
+ @"Data Source=D:\YourFile.xls;"
+ @"Extended Properties=""Excel
8.0;HDR=Yes;IMEX=1;""");
excelConnection.Open();
try
{
OleDbDataAdapter dbAdapter =
new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelConnection);
dbAdapter.Fill(dt);
}
finally
{
excelConnection.Close();
}
return dt;
}
Post Reference: Vikram Aristocratic Elfin Share
Saturday, June 11, 2011
Stuff function in SQL SERVER
The STUFF function inserts a set of characters into a given string at a given position
STUFF(character_expression1, start, length, character_expression2)
Character_Expression1 represents the string in which the stuff is to be applied. start indicates the starting position of the character in character_expression1, length is the length of characters which need to be replaced. character_expression2 is the string that will be replaced to the start position
1) SELECT STUFF('Fun', 1, 0, '*')
the output will be : *Fun.
2) SELECT STUFF('SQL SERVER is USEFUL',5,6,'DATABASE')
the output will be : SQL DATABASE is USEFUL
Post Reference: Vikram Aristocratic Elfin Share
Tuesday, April 26, 2011
How to use ORDER BY when Defining a View?
If you use Order By clause while creating SQL View, SQL Server throw you such kind of error
Post Reference: Vikram Aristocratic Elfin Share
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
Sloution: Use Top with Percent keyword while creating view. For example-
Create View
As (Select Top 100 Percent col1, col2, col3 from Table11 order by col1,col2,col3)
Can We Insert Data into a View?
We can not insert data into view instead we can insert data into the underline table of view. SQL Server will
allow you to insert data into the underlying table through a view with a condition:
*The insert columns must be limited to columns of a single underlying table:- This means if a view is composed of 2 or more tables then insert should be made to column of one table at time.
For example
SELECT tb1.tab1_id, tb2.tab2_id, tb1.value tab1_value, tb2.value
tab2_value
FROM table1 tb1
INNER JOIN table2 tb2
Where tb1.tab1_id=tb2.tab1_id
This is a view "vTest" made from two table table1 and table2 inner joined on
tab1_id field
Now if you insert data from view to underlying table of table1 and Table2 you
need to do this in this way:
INSERT INTO vTest (tab1_id, tab1_value) VALUES (3, 30);
INSERT INTO vTest (tab2_id, tab1_id, tab2_value) VALUES (1,3, 30);
Post Reference: Vikram Aristocratic Elfin Share
Monday, April 4, 2011
Get Ping with every DML statement on your table.....TRIGGERS
A trigger is a database object that is Bind to a table. In many aspects it is similar to a stored procedure and are often referred to as a "special kind of stored procedure."
Modifications to the table are made using INSERT,UPDATE,OR DELETE statements.Triggers are used to enforce data integrity and business rules such as automatically updating summary data. It allows to perform cascading delete or update operations. If constraints exist on the trigger table,they are checked prior to the trigger execution. If constraints are violated statement will not be executed and trigger will not run.Triggers are associated with tables and they are automatic . Triggers are automatically invoked by SQL SERVER. Triggers prevent incorrect , unauthorized,or inconsistent changes to data.
SQL Server has many types of triggers:
1)Working with INSERT Triggers
CREATE TRIGGER invoiceUpdate ON [Orders]
FOR INSERT
AS
Begin
UPDATE p SET p.instock=[p.instock – i.qty]
FROM products p JOIN inserted I ON p.prodid = i.prodid
End
You created an INSERT trigger that referenced the logical inserted table. Whenever you insert a new record in the orders table now, the corresponding record in the products table will be updated to subtract the quantity of the order from the quantity on hand in the instack coloumn of the products table.
2)Working with DELETE Triggers
DELETE triggers are used for restricting the data that your users can remove from a database. For example
CREATE TRIGGER VikramDelete ON [Customers]
FOR DELETE
AS
IF (SELECT name FROM deleted) = ‘Vikram’
BEGIN
PRINT ‘Danger...Can not remove customers with the name vikram’
PRINT ‘Transaction has been canceled’
ROOLBACK
END
DELETE trigger used the logical deleted table to make certain that you were not trying to delete a customer with a great name “Vikram” – if you did try to delete such a customer, you would be met with Anaconda in the form of an error message (which was generated by the PRINT statement that you entered in the trigger code).
3)Working with UPDATE Triggers
UPDATE triggers are used to restrict UPDATE statement issued by your users, or to back your previous data.
CREATE TRIGGER CheckStock ON [Products]
FOR UPDATE
AS
IF (SELECT InStock FROM inserted) < 0
BEGIN
PRINT ‘Cannot oversell Products’
PRINT ‘Transaction has been cancelled’
ROLLBACK
END
You created an UPDATE trigger that references the inserted table to verify that you are not trying to insert a value that is less than zero. You need to check only the inserted table because SQL Server performs any necessary mathematical functions before inserting your data.
Since I am running out of time, in next post i will try to explain INSTEAD OF TRIGGER.
Post Reference: Vikram Aristocratic Elfin Share
BlueTangledKindle Wireless Reading Device, Wi-Fi, Graphite, 6" Display with New E Ink Pearl Technology
Modifications to the table are made using INSERT,UPDATE,OR DELETE statements.Triggers are used to enforce data integrity and business rules such as automatically updating summary data. It allows to perform cascading delete or update operations. If constraints exist on the trigger table,they are checked prior to the trigger execution. If constraints are violated statement will not be executed and trigger will not run.Triggers are associated with tables and they are automatic . Triggers are automatically invoked by SQL SERVER. Triggers prevent incorrect , unauthorized,or inconsistent changes to data.
SQL Server has many types of triggers:
- After Trigger
- Multiple After Triggers
- Instead Of Triggers
- Mixing Triggers Type
- Triggers can update, insert, or delete data in the same or other tables. This is useful to maintain relationships between data or to keep audit trail information.
- Triggers can check data against values of data in the rest of the table or in other tables. This is useful when you cannot use RI constraints or check constraints because of references to data from other rows from this or other tables.
- Triggers can use user-defined functions to activate non-database operations. This is useful, for example, for issuing alerts or updating information outside the database.
- Note: An AFTER trigger can be created only on tables, not on views.
1)Working with INSERT Triggers
CREATE TRIGGER invoiceUpdate ON [Orders]
FOR INSERT
AS
Begin
UPDATE p SET p.instock=[p.instock – i.qty]
FROM products p JOIN inserted I ON p.prodid = i.prodid
End
You created an INSERT trigger that referenced the logical inserted table. Whenever you insert a new record in the orders table now, the corresponding record in the products table will be updated to subtract the quantity of the order from the quantity on hand in the instack coloumn of the products table.
2)Working with DELETE Triggers
DELETE triggers are used for restricting the data that your users can remove from a database. For example
CREATE TRIGGER VikramDelete ON [Customers]
FOR DELETE
AS
IF (SELECT name FROM deleted) = ‘Vikram’
BEGIN
PRINT ‘Danger...Can not remove customers with the name vikram’
PRINT ‘Transaction has been canceled’
ROOLBACK
END
DELETE trigger used the logical deleted table to make certain that you were not trying to delete a customer with a great name “Vikram” – if you did try to delete such a customer, you would be met with Anaconda in the form of an error message (which was generated by the PRINT statement that you entered in the trigger code).
3)Working with UPDATE Triggers
UPDATE triggers are used to restrict UPDATE statement issued by your users, or to back your previous data.
CREATE TRIGGER CheckStock ON [Products]
FOR UPDATE
AS
IF (SELECT InStock FROM inserted) < 0
BEGIN
PRINT ‘Cannot oversell Products’
PRINT ‘Transaction has been cancelled’
ROLLBACK
END
You created an UPDATE trigger that references the inserted table to verify that you are not trying to insert a value that is less than zero. You need to check only the inserted table because SQL Server performs any necessary mathematical functions before inserting your data.
Since I am running out of time, in next post i will try to explain INSTEAD OF TRIGGER.
Post Reference: Vikram Aristocratic Elfin Share
BlueTangledKindle Wireless Reading Device, Wi-Fi, Graphite, 6" Display with New E Ink Pearl Technology
Sunday, March 20, 2011
How SQL Azure different from my SQL Server ??.. SQL Azure vs SQL Server
Similarities and Differences
Similar to an instance of SQL Server on your premises, SQL Azure exposes a tabular data stream (TDS) interface for Transact-SQL-based database access. This allows your database applications to use SQL Azure in the same way that they use SQL Server. Since SQL Azure is a service, administration in SQL Azure is slightly different.Unlike administration for an on-premise instance of SQL Server, SQL Azure abstracts the logical administration from the physical administration; you continue to administer databases, logins, users, and roles, but Microsoft administers and configures the physical hardware such as hard drives, servers, and storage. This approach helps SQL Azure provide a large-scale multi-tenant database service that offers enterprise-class availability, scalability, security, and self-healing.
Since Microsoft handles all of the physical administration, there are some differences between SQL Azure and an on-premise instance of SQL Server in terms of administration, provisioning, Transact-SQL support, programming model, and features. For more information, see Guidelines and Limitations (SQL Azure Database).
Logical Administration vs. Physical Administration
Although SQL Azure plays an active role in managing the physical resources of the database, the DBA plays a very important role in administering SQL Azure-based database applications. Using SQL Azure, DBAs manage schema creation, statistics management, index tuning, query optimization, and security administration (logins, users, roles, etc.). For more information about security administration in SQL Azure, see Managing Logins and Users in SQL Azure.Database administration in SQL Azure differs most from SQL Server in terms of physical administration. SQL Azure automatically replicates all data to provide high availability. SQL Azure also manages load balancing and, in case of a server failure, transparent fail-over to a healthy machine hosting one of the backup copies of your database.
To provide this level of physical administration, you cannot control the physical resources of SQL Azure. For example, you cannot specify the physical hard drive or file group where a database or index will reside. Because the computer file system is not accessible and all data is automatically replicated, SQL Server backup and restore commands are not applicable to SQL Azure. The SQL Azure service still backs up all databases; however they are not accessible to regular users. This is a feature that may be offered in future.
Starting with SQL Azure Service Update 4, SQL Azure allows you to back up your database by copying it to a new database in SQL Azure. For more information, see Copying Databases in SQL Azure.
For more information on the available options to transfer data to SQL Azure, see Migrating Databases to SQL Azure.
Provisioning
When preparing an on-premises SQL Server deployment, it may be the role of the DBA or IT department to prepare and configure the required hardware and software. When using SQL Azure, these tasks are performed by the SQL Azure provisioning process.You can begin provisioning your SQL Azure databases after you create a Windows Azure Platform account. This account allows you to access all the services, such as Windows Azure, AppFabric, and SQL Azure, and is used to set up and manage your subscriptions.
Each SQL Azure subscription is bound to one SQL Azure server within one of the Microsoft data centers. Your SQL Azure server is an abstraction that defines a grouping of databases. To enable load-balancing and high availability, databases associated with your SQL Azure server may reside on separate physical computers within the Microsoft data center.
For more information about provisioning, see SQL Azure Provisioning Model.
Transact-SQL Support
Transact-SQL is a language that contains commands used to administer instances of SQL Server including creating and managing all objects in an instance of SQL Server, and inserting, retrieving, modifying, and deleting all data in tables. Applications can communicate with an instance of SQL Server by sending Transact-SQL statements to the server. Microsoft SQL Azure Database supports a subset of Transact-SQL for SQL Server. For more information about Transact-SQL support, see Transact-SQL Support (SQL Azure Database).Features and Types
SQL Azure does not support all of the features and data types found in SQL Server. Analysis Services, Replication, and Service Broker are not currently provided as services on the SQL Azure. You can connect from on-premises Analysis Server to SQL Azure and SQL Azure can be used either as a data source or destination. When this article is being updated, the Customer Technology Preview of SQL Azure Reporting is also available. Microsoft SQL Azure Reporting is a cloud-based reporting service built on SQL Azure, SQL Server, and SQL Server Reporting Services technologies. You can publish, view, and manage reports that display data from SQL Azure data sources.Because SQL Azure performs the physical administration, any statements and options that attempt to directly manipulate physical resources will be blocked, such as Resource Governor, file group references, and some physical server DDL statements. It is also not possible to set server options and SQL trace flags or use the SQL Server Profiler or the Database Tuning Advisor utilities.
Key Benefits of the Service
The benefits of using SQL Azure include manageability, high availability, scalability, a familiar development model, and a relational data model.Self-Managing
SQL Azure offers the scale and functionality of an enterprise data center without the administrative overhead that is associated with on-premise instances of SQL Server. This self-managing capability enables organizations to provision data services for applications throughout the enterprise without adding to the support burden of the central IT department or distracting technology-savvy employees from their core tasks in order to maintain a departmental database application.With SQL Azure, you can provision your data storage in minutes. This reduces the initial costs of data services by enabling you to provision only what you need. When your needs change, you can easily extend your cloud-based data storage to meet those needs.
High Availability
SQL Azure is built on proven Windows Server and SQL Server technologies, and is flexible enough to cope with any variations in usage and load. The service replicates multiple redundant copies of your data to multiple physical servers to maintain data availability and business continuity. In the case of a hardware failure, SQL Azure provides automatic failover to ensure availability for your application.Scalability
A key advantage of SQL Azure is the ease with which you can scale your solution. As data grows, databases need to either scale up or scale out. Scale up always has a ceiling whereas scale out has no virtual limits. A common scale out technique is data-partitioning. After partitioning your data, the service scales as your data grows. A pay-as-you-grow pricing model makes sure that you only pay for the storage that you use, so that you can also scale down the service when you do not need it.Familiar Development Model
When developers create on-premise applications that use SQL Server, they use client libraries like ADO.NET, ODBC that use the tabular data stream (TDS) protocol to communicate between client and server. SQL Azure provides the same TDS interface as SQL Server so that you can use the same tools and libraries to build client applications for data that is stored in SQL Azure. For more about TDS, see Network Protocols and TDS Endpoints.Relational Data Model
SQL Azure will seem very familiar to developers and administrators because data is stored in SQL Azure just like it is stored in SQL Server, by using using Transact-SQL. Conceptually similar to an on-premise instance of SQL Server, a SQL Azure server is logical group of databases that acts as an authorization boundary.Within each SQL Azure server, you can create multiple databases that have tables, views, stored procedures, indices, and other familiar database objects. This data model makes good use of your existing relational database design and Transact-SQL programming skills, and simplifies the process of migrating existing on-premise database applications to SQL Azure. For more about Transact-SQL and its relationship to SQL Azure, see Transact-SQL Support (SQL Azure Database).
SQL Azure servers and databases are virtual objects that do not correspond to physical servers and databases. By insulating you from the physical implementation, SQL Azure enables you to spend time on your database design and adding additional value to the business.
The following table provides a high-level comparison between SQL Azure and SQL Server. For the most up-to-date and detailed information, see the following topics on MSDN:
- Accounts and Billing in SQL Azure
- Guidelines and Limitations in SQL Azure
- Tools and Utilities Support in SQL Azure
- Transact-SQL Reference Support in SQL Azure
- SQL Server Feature Limitations (SQL Azure Database)
Post Reference: Vikram Aristocratic Elfin Share
BurlesqueKindle 3G Wireless Reading Device, Free 3G + Wi-Fi, 3G Works Globally, Graphite, 6" Display with New E Ink Pearl Technology
What SQL Azure Database ??
Microsoft SQL Azure Database is a database service provided as part of the Windows Azure Platform. It is based on Microsoft SQL Server, and provides many of the same features. Unlike SQL Server, which is provided as a software package that you install and maintain, SQL Azure Database is provided as a service that is hosted on hardware in Microsoft datacenters. SQL Azure takes care of maintaining the hardware and software layer, freeing you to concentrate on database design.
Since SQL Azure maintains the hardware and software for your database, provisioning a new database is very straightforward and easy; you request a new database and Microsoft provisions one automatically for you. Data stored in SQL Azure Database is also highly available, as each database hosted in the Microsoft data center has three copies: one primary and two secondary replicas. All reads and writes go through the primary, and any changes are replicated to the secondary replicas asynchronously.
Kindle Wireless Reading Device, Wi-Fi, Graphite, 6" Display with New E Ink Pearl Technology
Post Reference: Vikram Aristocratic Elfin Share
Since SQL Azure maintains the hardware and software for your database, provisioning a new database is very straightforward and easy; you request a new database and Microsoft provisions one automatically for you. Data stored in SQL Azure Database is also highly available, as each database hosted in the Microsoft data center has three copies: one primary and two secondary replicas. All reads and writes go through the primary, and any changes are replicated to the secondary replicas asynchronously.
Kindle Wireless Reading Device, Wi-Fi, Graphite, 6" Display with New E Ink Pearl Technology
Post Reference: Vikram Aristocratic Elfin Share
Thursday, March 17, 2011
When to TRUNCATE and when to DELETE ??
Difference between Truncate and Delete in SQL
Post Reference: Vikram Aristocratic Elfin Share
Tuesday, January 11, 2011
How SQL Server evaluate Null Value in Check Condition
Understanding NULL value with check constraint
As I said earlier when the condition of check constraint evaluates to false, it will not allow inserting /updating record in the table.
In the given below example I am creating a check constraint which is allowing only three word in the country field.
Alter table MyCountry
Add check (country_name in (‘india’, ’usa’, ’uk ’))
Now I am trying to insert these three record using insert statement
insert into MyCountry(country_name) values(‘india’)
insert into MyCountry(country_name) values(NULL)
insert into MyCountry(country_name) values(‘uss’)
Now what will happen, when I will try to execute these three insert statement:
a) Only first insert statement insert record.
b) First and second insert record.
c) First and third insert record successfully.
The correct solution is (b).
The reason the second INSERT statement worked is that the check constraint did not equate to FALSE when the second INSERT statement was run. Because of this, the database engine inserted the record. So why did this happen? This happened because when NULL is used in a comparison operation it equates to UNKNOWN. Since UNKNOWN is not FALSE there is no violation of the check constraint. Therefore, you need to be careful when you write your check constraints where you want to reject values that contain NULLS. Another way to code the above constraint is
Alter table MyCountry
Add check (country_name in (‘india’, ’usa’, ’uk ’) and country_name is not NULL)
Post Reference: Vikram Aristocratic Elfin Share
Monday, January 10, 2011
Predefined value for a column in SQL Server Table object
How to set predefined value for a column in SQL Server Table object
Check constraints contain an expression the database will evaluate when you modify or insert a row. You can use any of the operator (<, >, <=, >=, IN, Like, Between, AND, OR) to build your check constraint expression. Only when the expression in check constraint evaluates to true, you will be allowed to insert or update record in the table whereas if check constraint expression evaluate to false you will not allowed enter/update record in the table.
You can add check constraint for your column in 3 ways: column level, table level or using alter table statement.
1) Column level
Create table ActivityMaster
(
activity_id int,
activity_name check (activity_name in (‘cricket’, ’tt’, ’swimming ’))
}
2)Table Level
Create table ActivityMaster
(
activity_id int,
activity_name,
constraint chkActivityName check (activity_name in (‘cricket’, ’tt’, ’swimming ’))
}
3)In Alter Statement
Alter table ActivityMaster
Add check (activity_name in (‘cricket’, ’tt’, ’swimming ’))
Here in the above example we are having a table called ActivityMaster which contain two column activity_id and activity_name then we are adding check constraint with activity_name which says, the activity_name column cannot have other than (‘cricket’, ’tt’, ’swimming ’).
Some more use of Check
We can have multiple use of check constraint say salary should be greater than 3000
Alter table EmployeeSalary
Add check (emp_salary > 3000)
You can also use ‘AND’ and ‘OR’ operator with check constraint.
Alter table EmployeeSalary
Add check (emp_salary >= 3000 AND emp_salary <= 90000 )
Two or more column in single Check
You can have multiple columns in a single check constraint like the one below
Alter table EmployeeSalary
Add check (emp_salary > 10000 and emp_post like ‘manager’)
Wednesday, January 5, 2011
What is Common Table Expression(CTE) in SQL Server?
There are often times when we may need to operate over a set of data that doesn't inherently exist within the system. For example say InvoiceDatabase where we may have tables like Order, OrderDtail, InvoiceMaster, InvoiceDetail but we may need to run report against aggregate data across these tables.
Typically, views are used to break down complex queries into desired set of data but again views are parmanent database objects with will occupy the database space. Then you are left with #temp table option, here also you need to write the whole create table then you need to insert record to the temporary table...
The CTE is a form of the derived table that can be declared once and referenced multiple times in a query.
A Simple Common Table Expression Example
TempCTE(StreamName,IsActive)as(
select top 5 sm.StreamName, ssm.SubStreamName from StreamMaster sm, SubStreamMaster ssmwhere sm.StreamId=ssm.StreamId )
select * from Temp CTE
StreamName SubStreamName
12th Science B
12th Science A
12th Science AB
12th General General
12th General Home Science
Common Table Expression Syntax
A Common Table Expression contains three core parts:
with abc(StreamName,IsActive)as(
select top 5 sm.StreamName, ssm.SubStreamName from StreamMaster sm, SubStreamMaster ssmwhere sm.StreamId=ssm.StreamId )select * from StreamMasterselect * from abc
Post Reference: Vikram Aristocratic Elfin Share
This query creates a CTE named
with
Typically, views are used to break down complex queries into desired set of data but again views are parmanent database objects with will occupy the database space. Then you are left with #temp table option, here also you need to write the whole create table then you need to insert record to the temporary table...
The CTE is a form of the derived table that can be declared once and referenced multiple times in a query.
A Simple Common Table Expression Example
TempCTE(StreamName,IsActive)as(
select top 5 sm.StreamName, ssm.SubStreamName from StreamMaster sm, SubStreamMaster ssmwhere sm.StreamId=ssm.StreamId )
select * from Temp CTE
StreamName SubStreamName
12th Science B
12th Science A
12th Science AB
12th General General
12th General Home Science
Common Table Expression Syntax
A Common Table Expression contains three core parts:
- The CTE name (this is what follows the
WITH
keyword) - The column list (optional)
- The query (appears within parentheses after the
AS
keyword)
with abc(StreamName,IsActive)as(
select top 5 sm.StreamName, ssm.SubStreamName from StreamMaster sm, SubStreamMaster ssmwhere sm.StreamId=ssm.StreamId )select * from StreamMasterselect * from abc
Post Reference: Vikram Aristocratic Elfin Share
This query creates a CTE named
TempCTE t
hat returns top 5 StreamName with there sub-stream name. Now you can query the TempCTE to get the resultant data.with
Difference between varchar and nvarchar?
Storing Unicode Data
varchar: Variable-length, non-Unicode character data. varchar stores unicode data.nvarchar: Variable-length Unicode character data. nvarchar stores unicode.
If you are using vchar datatype then each time you store data you first need the data to be converted into varchar then only you can store, this is not apply to nvarchar.
So if you are using nvarchar lot of your conversion task will be reduced. But nvarchar takes twice as much space as varchar, so before using this datatype considered this point.
With cheap memory nowadays I prefer nvarchar.
Post Reference: Vikram Aristocratic Elfin Share
Tuesday, January 4, 2011
Export Data form Sql Server to Excel Datasheet
Do The Following Step to Export Data from Sql Server to Excel
1)Create an Excel Datasheet save it with name testingExcel in D:/testingExcel.xls2)Save Type of excel sheet should be Excel 97-2003 Worbook.
3)Then enable the 'ad hoc distributed queries' in surface area configuration using sp_configure
EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
4)Then with the help of openrowset function you can insert the data of sql server table to worksheet. Yet not finished you have to create column in excel sheet with the name StreamName and IsActive
INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=D:\testingExcel.xls;','SELECT StreamName,IsActive FROM [Sheet1$]') select StreamName,IsActive from StreamMaster
go
5)Be sure you have closed your excel sheet befor executing the above query.
6) Thats all you need to do to export data to excel sheet.
Post Reference: Vikram Aristocratic Elfin Share
Friday, December 31, 2010
What is Google Updater? Is it worth for me?
If you have dowloaded any of the goole application, then checkout there is process running in your PC googleupdater.exe by typing service.msc in your run command. Or you can also check by pressing “alt+ctrl+del” to open task manager and click the process tab.
So, google updater is like all those unwanted tiny applications which keeps on running in the background and making your system slow.
Post Reference: Vikram Aristocratic Elfin Share
What is Google Updater?
This is a process that google gives you, which is not at all necessuary to be run all the time when you use any of the google application you have downloaded. Then the question is What it do?Why this is running on my Desktop?
This process informs the user about the new version and updates for the all the google products installed on your PC.Is it a worthfull to have this process running on my Desktop?
Normally when ever you use any of the google products like picasa or google screensaver you can manually update these applications but google updater on the other hand keeps on running and consuming the system resources like physical memory like RAM all the time.So, google updater is like all those unwanted tiny applications which keeps on running in the background and making your system slow.
Post Reference: Vikram Aristocratic Elfin Share
Where is Google
Facebook tops Google in website hits: study
January 1, 2011 - 7:05AM
Facebook stole the thunder from Google this year as the most-visited website in the United States, according to a new study from Internet research firm Experian Hitwise.
The social-networking juggernaut's www.facebook.com was the top-visited website for the first time and accounted for 8.93 percent of all US visits between January and November 2010, Experian Hitwise said.
Google, the world's Internet search leader, slid to second place. Google.com drew 7.19 percent of visits, followed by Yahoo! Mail (3.52 percent), Yahoo! (3.30 percent) and YouTube (2.65 percent).
Facebook led arch-rival Google in the number of hits per month since March.
However, taking into account all of Google's websites, such as YouTube and Gmail, the Mountain View, California-based company drew 9.85 percent of the US visits, ahead of Facebook's 8.93 percent and the 8.12 percent garnered by Yahoo! sites, an Experian Hitwise spokesman said Friday.
Online tracking firm comScore last week ranked the Yahoo! family of websites as the most-visited in the US in November, ahead of Google, Microsoft websites and Facebook.
On a global scale, Google held the top position, followed by Microsoft, Facebook and Yahoo!, according to comScore.
But analyst Greg Sterling of the specialist site SearchEngineLand.com cautioned that the Hitwise study does not track website visits via mobile devices such as cell phones or tablets, and the number of searches on Google's Chrome browser, which avoids google.com, was uncertain.
"This is right now more symbolic than anything" to see Facebook overtake Google in the United States, Sterling told AFP, adding that the study confirms "Facebook growth has been dramatic."
The social-networking giant has more than 500 million active users per month in the world, and according to comScore attracted 647.5 million unique visits in November, a jump of 48 percent from a year ago.
Sterling highlighted the sharply different approaches between Google and Facebook.
"Google is a very utilitarian site, where people go to make a decision, whereas Facebook is for entertainment," he said.
But if Facebook "were to concentrate on search, they could do something that stands to really hurt Google."
The social-networking juggernaut's www.facebook.com was the top-visited website for the first time and accounted for 8.93 percent of all US visits between January and November 2010, Experian Hitwise said.
Google, the world's Internet search leader, slid to second place. Google.com drew 7.19 percent of visits, followed by Yahoo! Mail (3.52 percent), Yahoo! (3.30 percent) and YouTube (2.65 percent).
However, taking into account all of Google's websites, such as YouTube and Gmail, the Mountain View, California-based company drew 9.85 percent of the US visits, ahead of Facebook's 8.93 percent and the 8.12 percent garnered by Yahoo! sites, an Experian Hitwise spokesman said Friday.
Online tracking firm comScore last week ranked the Yahoo! family of websites as the most-visited in the US in November, ahead of Google, Microsoft websites and Facebook.
On a global scale, Google held the top position, followed by Microsoft, Facebook and Yahoo!, according to comScore.
But analyst Greg Sterling of the specialist site SearchEngineLand.com cautioned that the Hitwise study does not track website visits via mobile devices such as cell phones or tablets, and the number of searches on Google's Chrome browser, which avoids google.com, was uncertain.
"This is right now more symbolic than anything" to see Facebook overtake Google in the United States, Sterling told AFP, adding that the study confirms "Facebook growth has been dramatic."
The social-networking giant has more than 500 million active users per month in the world, and according to comScore attracted 647.5 million unique visits in November, a jump of 48 percent from a year ago.
Sterling highlighted the sharply different approaches between Google and Facebook.
"Google is a very utilitarian site, where people go to make a decision, whereas Facebook is for entertainment," he said.
But if Facebook "were to concentrate on search, they could do something that stands to really hurt Google."
© 2011 AFP
This story is sourced direct from an overseas news agency as an additional service to readers. Spelling follows North American usage, along with foreign currency and measurement units.
This story is sourced direct from an overseas news agency as an additional service to readers. Spelling follows North American usage, along with foreign currency and measurement units.
Post Reference: Vikram Aristocratic Elfin Share
Thursday, December 30, 2010
Getting column/field list in sql server table
How to get list of fields under a table
It is very simple to get list of fields or column under a sql server table. With the help of sys object we can get the column list. Here is an example:
select * from syscolumns where id =
(select id from sysobjects where type='U' and name like 'SSC_School1')
OR
select * from syscolumns where id =
(select object_id from sys.objects where type='U' and name like 'SSC_School1')
OR
select * from sys.columns where object_id =
(select object_id from sys.objects where type='U' and name like 'SSC_School1')
Here 1) type refer to object (sql server object like table, sp etc) and 'U' refer to user defined table
2) name refer to your Table name.
Post Reference: Vikram Aristocratic Elfin Share
Tuesday, December 28, 2010
Case in Sorting
Consider a situation where you need to display the records of employee table order by Address however you want first it should display all the records with INDIA in address field then USA then UK and after that all in sorted fashion.
You query this very easily by using case in order by clause. Here is an example:
select * from TempTable
order by (case id
when 'INDIA' then 1
when 'USA' then 2
when 'UK' then 3
end), id
Here 1,2,3 will specify the position of record with the condition India,USA and UK. It will first display the record of India, then USA then UK then rest all in sorted order.
Post Reference: Vikram Aristocratic Elfin Share
Monday, December 27, 2010
Understanding Sys.Object
Sys.Object table contains one row for each object that is created within a database, such as a constraint, default, log, rule, and stored procedure and so on.
select * from sys.objects
This will result all the object that is created within a database.
The’ type’ column in sys.objects table tell about object type for example ‘p’ indicate procedures, there is a ‘type_desc’ column that will describe the type.
select [name] from sys.objects where type = 'p'
This will result all the stored procedure that the user has created within a database.
This is the list of all possible values for this column (type):
• C = CHECK constraint
• D = Default or DEFAULT constraint
• F = FOREIGN KEY constraint
• L = Log
• P = Stored procedure
• PK = PRIMARY KEY constraint
• RF = Replication filter stored procedure
• S = System table
• TR = Trigger
• U = User table
• UQ = UNIQUE constraint
• V = View
• X = Extended stored procedure
We can also directly query sys.procedure table to get all the stored procedure that is created by user within a database.
select * from sys.procedures
Same way we can query sys.foreign_key to get all foreign key constraint created by user within a database.
select * from sys.foreign_keys
Sys.procedure
Understanding Sys.Object
Sunday, December 26, 2010
Create SQL SERVER Login
Steps to create Login
First Requirement
1.Login with window authentication.
2.Open object explorer.
3.Go to server and do right click -> Property.
4.In property Window -> go to security tab-> select “SQL Server and Window authentication mode”
5.Press ok
Second Requirement
1.Go the server in object explorer
2.Then go to “security tab” -> login.
3.Right click login -> Crete new login.
4.In Login New window ->Go to General tab
5.Give “Login name “You want to create. -> Then select Sql server Authentication -> give password.
6.Then uncheck “Enforce password policy”
7.Then set default database for which u want to create login.
8.Then Go to “Server Role” tab. Check all the sever role u want to give to the logger.
9.Then Go to “User Mapping” and select the database -> set user(the new logger)-> default schema (set to dbo)
10.Then give database role membership for the database u selected.
11.Then go to “Status” tab set “Grant” permission to connect to database engine.
12.And set login enabled.
This is all you need to do to create new login.
Now you can login in server authentication mode with the new login name u just created.
Error: 18456
If you encounter login fail with the new login name u just created with error code:18456
Step to Resolve
1.Then go to Start-> Microsoft SQL Server 2008 -> Configuration Tool -> Sql Server Configuration Manager.
2.Enabled TCP/IP and Named Pipe protocol
3.Then restart Sql server service.
That all you need to do to make your login success.
Post Reference: Vikram Aristocratic Elfin Share
Friday, December 24, 2010
Optimize Your Stored Procedure
This are few ways how you can optimized your sql server stored procedure, there are many other ways, for optimizing your stored procedure.
CREATE PROC dbo.ProcName
AS
SET NOCOUNT ON;
--Procedure code here
SELECT column1 FROM dbo.TblTable1
-- Reset SET NOCOUNT to OFF
SET NOCOUNT OFF;
GO
SELECT * FROM dbo.MyTable -- Preferred method
-- Instead of
SELECT * FROM MyTable -- Avoid this method
--And finally call the stored procedure with qualified name like:
EXEC dbo.MyProc -- Preferred method
--Instead of
EXEC MyProc -- Avoid this method
IF EXISTS (SELECT 1 FROM sysobjects
WHERE name = 'MyTable' AND type = 'U')
DECLARE @Query VARCHAR(100)
DECLARE @Age INT
SET @Age = 25
SET @Query = 'SELECT * FROM dbo.tblPerson WHERE Age = ' + CONVERT(VARCHAR(3),@Age)
EXEC (@Query)
If we again execute the above batch using different @Age value, then the execution plan for SELECT statement created for @Age =25 would not be reused. However, if we write the above batch as given below,
DECLARE @Query NVARCHAR(100)
SET @Query = N'SELECT * FROM dbo.tblPerson WHERE Age = @Age'
EXECUTE sp_executesql @Query, N'@Age int', @Age = 25
the compiled plan of this SELECT statement will be reused for different value of @Age parameter. The reuse of the existing complied plan will result in improved performance.
BEGIN TRY
--Your t-sql code goes here
END TRY
BEGIN CATCH
--Your error handling code goes here
END CATCH
Post Reference: Vikram Aristocratic Elfin Share
* Include SET NOCOUNT ON statement
: With every SELECT and DML statement, the SQL server returns a message that indicates the number of affected rows by that statement. This information is mostly helpful in debugging the code, but it is useless after that. By setting SET NOCOUNT ON, we can disable the feature of returning this extra information. For stored procedures that contain several statements or contain Transact-SQL loops, setting SET NOCOUNT to ON can provide a significant performance boost because network traffic is greatly reduced.CREATE PROC dbo.ProcName
AS
SET NOCOUNT ON;
--Procedure code here
SELECT column1 FROM dbo.TblTable1
-- Reset SET NOCOUNT to OFF
SET NOCOUNT OFF;
GO
* Use schema name with object name:
The object name is qualified if used with schema name. Schema name should be used with the stored procedure name and with all objects referenced inside the stored procedure. This help in directly finding the complied plan instead of searching the objects in other possible schema before finally deciding to use a cached plan, if available. This process of searching and deciding a schema for an object leads to COMPILE lock on stored procedure and decreases the stored procedure’s performance. Therefore, always refer the objects with qualified name in the stored procedure likeSELECT * FROM dbo.MyTable -- Preferred method
-- Instead of
SELECT * FROM MyTable -- Avoid this method
--And finally call the stored procedure with qualified name like:
EXEC dbo.MyProc -- Preferred method
--Instead of
EXEC MyProc -- Avoid this method
* Do not use the prefix “sp_” in the stored procedure name:
If a stored procedure name begins with “SP_,” then SQL server first searches in the master database and then in the current session database. Searching in the master database causes extra overhead and even a wrong result if another stored procedure with the same name is found in master database.* Use IF EXISTS (SELECT 1) instead of (SELECT *):
To check the existence of a record in another table, we uses the IF EXISTS clause. The IF EXISTS clause returns True if any value is returned from an internal statement, either a single value “1” or all columns of a record or complete recordset. The output of the internal statement is not used. Hence, to minimize the data for processing and network transferring, we should use “1” in the SELECT clause of an internal statement, as shown below:IF EXISTS (SELECT 1 FROM sysobjects
WHERE name = 'MyTable' AND type = 'U')
* Use the sp_executesql stored procedure instead of the EXECUTE statement.
The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve the re-usability of your code. The execution plan of a dynamic statement can be reused only if each and every character, including case, space, comments and parameter, is same for two statements. For example, if we execute the below batch:DECLARE @Query VARCHAR(100)
DECLARE @Age INT
SET @Age = 25
SET @Query = 'SELECT * FROM dbo.tblPerson WHERE Age = ' + CONVERT(VARCHAR(3),@Age)
EXEC (@Query)
If we again execute the above batch using different @Age value, then the execution plan for SELECT statement created for @Age =25 would not be reused. However, if we write the above batch as given below,
DECLARE @Query NVARCHAR(100)
SET @Query = N'SELECT * FROM dbo.tblPerson WHERE Age = @Age'
EXECUTE sp_executesql @Query, N'@Age int', @Age = 25
the compiled plan of this SELECT statement will be reused for different value of @Age parameter. The reuse of the existing complied plan will result in improved performance.
* Try to avoid using SQL Server cursors whenever possible:
Cursor uses a lot of resources for overhead processing to maintain current record position in a recordset and this decreases the performance. If we need to process records one-by-one in a loop, then we should use the WHILE clause. Wherever possible, we should replace the cursor-based approach with SET-based approach. Because the SQL Server engine is designed and optimized to perform SET-based operation very fast. Again, please note cursor is also a kind of WHILE Loop.* Keep the Transaction as short as possible:
The length of transaction affects blocking and deadlocking. Exclusive lock is not released until the end of transaction. In higher isolation level, the shared locks are also aged with transaction. Therefore, lengthy transaction means locks for longer time and locks for longer time turns into blocking. In some cases, blocking also converts into deadlocks. So, for faster execution and less blocking, the transaction should be kept as short as possible.* Use TRY-Catch for error handling:
Prior to SQL server 2005 version code for error handling, there was a big portion of actual code because an error check statement was written after every t-sql statement. More code always consumes more resources and time. In SQL Server 2005, a new simple way is introduced for the same purpose. The syntax is as follows:BEGIN TRY
--Your t-sql code goes here
END TRY
BEGIN CATCH
--Your error handling code goes here
END CATCH
Post Reference: Vikram Aristocratic Elfin Share
Subscribe to:
Posts (Atom)