Search this blog

Showing posts with label SQL Server 2005. Show all posts
Showing posts with label SQL Server 2005. Show all posts

Wednesday, October 6, 2010

Error: SQL Server Native Client cannot be found

Problem:
Today I tried to install SQL Server 2005 Developer edition in my system. During the installation, it throws the given error:


---------------------------
Microsoft SQL Server 2005 Setup
---------------------------
An installation package for the product Microsoft SQL Server Native Client cannot be found. Try the installation again using a valid copy of the installation package 'sqlncli.msi'.
---------------------------
OK
---------------------------

Cause:
System already contains another version of "SQL Server Native Client". So that it throws the error.

Solution:
Uninstall "SQL Server Native Client" thru "Add and Remove Programs"
Re-install SQL Server 2005 Again

Wednesday, June 23, 2010

Maximum number of Index per table

For SQL Server 2005:
1 Clustered Index + 249 Nonclustered Index = 250 Index
http://msdn.microsoft.com/en-us/library/ms143432(SQL.90).aspx


For SQL Server 2008:
1 Clustered Index + 999 Nonclustered Index = 1000 Index
http://msdn.microsoft.com/en-us/library/ms143432.aspx


Reference: http://blog.sqlauthority.com/2009/06/29/sql-server-maximum-number-of-index-per-table/

Wednesday, June 2, 2010

How To Stop Or Start Windows Service Thru SQL Script

This Article, helps to start a windows services thru SQL Script. To control the windows services, we can use SQL Server’s Extended Stored Procedure, xp_cmdshell

Through command prompt, we can control the services by using MS-DOS Commands

NET START - Start the specified network or local service.
NET STOP - Stop the specified network or local service.

To Execute MS-DOS Commands, we can use the Extended SP: xp_cmdshell

The following piece of script will helps to stop/Start a windows service. In this code, I planned to start or stop the Services of SQL Server Analysis Services

declare @CmdLine varchar(1024)
declare @Command varchar(100)
declare @RetInfo varchar(8000)
select @Command = 'net start MSSQLServerOLAPService'
print @Command
exec @RetInfo = master.dbo.xp_cmdshell @Command
print @RetInfo

When you Execute this code, you may face the following error like

Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1
SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.
For security reason, SQL Server blocked access to the Procedure xp_cmdshell


If you face this error, you can enable this feature By following piece of script:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

Now if you run the previous code, it will start your services.
Hope it helps!

Friday, May 14, 2010

SQL Server 2005 evaluation software - Expired

The SQL Server 2005 evaluation software is no longer available. Learn more about the enhancements and new features in SQL Server 2008.


Reference:
http://technet.microsoft.com/en-us/sqlserver/bb498185.aspx

Wednesday, May 5, 2010

Microsoft SQL Server JDBC Driver 3.0 - Windows & Unix

Microsoft has released a new Java Database Connectivity (JDBC) driver. The SQL Server JDBC Driver 3.0 download is available to all SQL Server users at no additional charge, and provides access to SQL Server 2008 R2, SQL Server 2008, SQL Server 2005 and SQL Server 2000 from any Java application, application server, or Java-enabled applet. This is a Type 4 JDBC driver that provides database connectivity through the standard JDBC application program interfaces (APIs) available in Java Platform, Enterprise Edition 5 and above.

This release of the JDBC Driver is JDBC 4.0 compliant and runs on the Java Development Kit (JDK) version 5.0 or later. It has been tested against major application servers including IBM WebSphere, and SAP NetWeaver.

Tuesday, April 27, 2010

Microsoft SQL Server Native Client

Microsoft SQL Server Native Client is DLL, it provides an access to the SQL Database. This DLL contains both the SQL OLE DB provider and SQL ODBC driver. This helps to connect Microsoft SQL Server 7.0/2000/2005/2008.
Download Microsoft SQL Server Native Client from the given link

SQL Server Native Client 2005:
X86 Package
X64 Package
IA64 Package


SQL Server Native Client 2008:
X86 Package
X64 Package
IA64 Package

Monday, December 21, 2009

Microsoft SQL Server Login Error

Problem:
When I create a data source of my SQL Server, it throws the following error
---------------------------
Microsoft SQL Server Login
---------------------------
Connection failed:
SQLState: '01000'
SQL Server Error: 1326
[Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).
Connection failed:
SQLState: '08001'
SQL Server Error: 17
[Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.



Solution:
After search in many sites, I got the solution for this problem.


In SQL Server 2008, we have to enable the TCP/IP protocol of the server instance.


To Enable,
* . Goto Start, Then All Programs
* . Select Microsoft SQL Server 2008, Then Configuration Tools,
* . Select SQL Server Configuration Manager
* . Select SQL Server Network Configuration,
* . Then Select the Instance of your SQL Server
* . Select The TCP/IP protocol, Right click and Enable It


After Enable, Restart your SQL Server services. Now if you create the connection, it works fine.



In SQL Server 2005,
* . Go to Surface Area Configuration Manager,
* . Here Remote connections are disabled by default. Look at the Database Engine -> Remote Connections option
* . Set local and remote connections to using both TCP/IP and Named pipes


After Set this option, Restart your SQL Server services, then create your connection


Hope it Helps!

Tuesday, November 24, 2009

Uninstall SQL Server 2005 - Manual Process

Here are the steps to uninstall SQL Server 2005 components manually.


In Add or Remove Programs, uninstall all SQL Server 2005 components in the following order:
• SQL Server 2005
• SQL Server 2005 Analysis Services
• SQL Server 2005 Reporting Services
• SQL Server 2005 Notification Services
• SQL Server 2005 Integration Services
• SQL Server 2005 Tools
• SQL Server 2005 Books Online
• MSXML 6.0 Parser
• SQLXML4
• SQL Server VSS Writer
• SQL Server 2005 Backward Compatibility
• Anything else that is related to SQL Server 2005
• SQL Server Native Client
• SQL Server setup support files
After uninstalled all the components listed above, Download and then install the Windows Installer Cleanup Utility

Run Windows Installer Cleanup Utility, Select the components related to SQL, and then click Remove. You can select multiple components by using CTRL key.


if you Remove button, it will throw warning message then click ok to accept


Hope it Helps!

Monday, November 9, 2009

SSIS 2008 Vs. SSIS 2005 - DATA PROVIDERS


When you create a Data Source in SQL Server Integration services (SSIS), there are default Data provider will be listings in the connection manager dialog window.


In 2008, some new providers are added, upgraded and removed.


Have a look at the exhibit,

Blue Box – Newly added Data Providers in SSIS 2008
Magenta Box – Upgraded Data Providers in SSIS 2008
Red Box – Removed Data Providers in SSIS 2008

SSIS 2008 - Data Provider List 


SSIS 2005 - Data Provider List


Wednesday, November 4, 2009

How To Disable and Enable Triggers In SQL Server

In our Project, we’ve created Trigger for generate the transactional log. This log will be updated, whenever new data has been “inserted” or “updated or deleted” the Existing Record by using application or manually by executing T-SQL queries via SQL Client tool.

Recently, we’ve planned to import huge data thru ETL from other databases. In this scenario, trigger will update all the data to transactional log table. So we don’t want keep this record in our transactional log. To avoid this, we planned to disable the trigger in our database.

I followed the given steps to disable/Enable the trigger.

To Find the List of Triggers, you can use the following Query.

SELECT * FROM sys.triggers

The given Query will list all the triggers, which are all existed in your current Databases as well as other information about the triggers.

 
“sys.triggers” System Table contains a column, Named as “is_disabled”, this column holds the status of the trigger, either enabled or disabled.

is_disabled = 0 Means Enabled
is_disabled = 1 Means Disabled

There are 2 ways to disable a trigger by following ways

  1. T-SQL Script
  2. SQL Server Management studio Dialog

To Disable a Trigger By T-SQL Script:

DISABLE TRIGGER UPDATE_PROGRAMREQUEST_DATA ON PROGRAMREQUEST

After Disabled, if you run this query, you can ensure that you disabled the proper trigger or not.

SELECT * FROM sys.triggers




To Disable a Trigger By SQL Server Management studio (SSMS) Dialog:

  1. Expand the Table node in SSMS, Which is associated with Trigger
  2. then select the trigger as shown in the exhibit and select disable





After Trigger has been disabled, trigger icon will change with Red down Arrow, as shown in the figure.

To Enable a Trigger By T-SQL Script:

ENABLE TRIGGER UPDATE_PROGRAMREQUEST_DATA ON PROGRAMREQUEST


To Enable a Trigger By SQL Server Management studio Dialog:

  1. Right click on the disabled trigger, then click “Enable”

Icon will be changed to normal mode, after enabled the trigger.

Hope it helps you!

Saturday, October 10, 2009

Basic Functions Of System Databases - SQL


What are the basic functions of master, msdb, tempdb databases?

Microsoft SQL Server has four system databases: 


Master - The master database records all of the system level information for a SQL Server system. It records all login accounts and all system configuration settings. Master is the database that records the existence of all other databases, including the location of the database files. 


Tempdb - tempdb holds all temporary tables and temporary stored procedures. It also fills any other temporary storage needs such as work tables generated by SQL Server. Tempdb is re-created every time SQL Server is started so the system starts with a clean copy of the database. 


By default, tempdb auto grows as needed while SQL Server is running. If the size defined for tempdb is small, part of your system processing load may be taken up with auto growing tempdb to the size needed to support your workload each time to restart SQL Server. You can avoid this overhead by using ALTER DATABASE to increase the size of tempdb.


Model - The model database is used as the template for all databases created on a system. When a CREATE DATABASE statement is issued, the first part of the database is created by copying in the contents of the model database, and then the remainder of the new database is filled with empty pages. Because tempdb is created every time SQL Server is started, the model database must always exist on a SQL Server system. 


Msdb - The msdb database is used by SQL Server Agent for scheduling alerts and jobs, and recording operators.

Friday, October 9, 2009

Database Replication - SQL

What is Database Replication?

It is a kind of Data Transformation Services and it is responsible for the process of copying/moving the data among the databases which may be in same or different server.

What are the Types of Replication available in SQL?

Replications are classified into following categories based on process it involved.

* Snapshot replication
* Transactional replication
* Merge replication

Snapshot replication:

It will distribute the data exactly from one database to another. It won’t monitor any changes like updating, deletion etc.., it can be used when data are infrequent. . It is often used for browsing data such as price lists, online catalog, or data for decision support where the current data is not required and data is used as read only.

Transactional replication:

Initially, it will start with snapshot replication, and then whenever data changes happen, it will capture the changes and the changes will be propagated to the subscribers.

Merge replication:

Merge replication is bit different than others, it is a 2 way process. This process distributing the data between publisher and subscriber, it allows the publisher and subscriber to update the data while connected or disconnected, and then merging the updates between the sites when they are connected.

Pass - Through Query In SQL

What is a pass-through query?

Microsoft SQL Server sends pass-through queries as un-interpreted query strings to an OLE DB data source. The query must be in a syntax the OLE DB data source will accept. A Transact-SQL statement uses the results from a pass-through query as though it is a regular table reference.

This example uses a pass-through query to retrieve a result set from a Microsoft Access version of the Northwind sample database.

SELECT * FROM
OpenRowset

(

'Microsoft.Jet.OLEDB.4.0', 'c:\northwind.mdb';'admin'; ''
,

'SELECT CustomerID, CompanyName FROM Customers WHERE Region = ''WA'' '

)


Cursor in SQL

What is Cursor?
Cursor is a SQL Objects and it is having Row by Row Scrolling behavior while processing on the result-set (Set of records). It will act as pointer and referencing to the each row at a time. We can change the reference to other row whenever need.

Types of Cursor in SQL:
Cursor is classified into following types which are Static, Dynamic, Forward-only and static.

Syntax:
DECLARE <Cursor_Name> CURSOR
[LOCAL | GLOBAL]
[FORWARD ONLY | SCROLL]
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]
[TYPE_WARNING]
FOR <Selecting Statements>
[FOR UPDATE [OF Column_name [,....N]]]
Sample Cursor Script:

Use AdventureWorks
GO
Declare DBLogCursr cursor
For Select top 10 * from dbo.DatabaseLog
Open DBLogCursr
Fetch Next From DBLogCursr
While @@FETCH_STATUS <> -1
Begin
Fetch Next From DBLogCursr
End
Close DBLogCursr
Deallocate DBLogCursr
GO

Note: Click on the image to see the Maximized View



To know more about cursor, please refer this documentation from

Disadvantages of Cursor:
  • Whenever fetch the record thru cursor, it will do the network roundtrip between server and client
  • Cursor need more temporary memory storage (For IO Operations)
  • Some restrictions are in select statement when we use with cursor
  • Cursor is not recommendable, because it will leads to performance issue
So Please use the cursor on critical situation. Hope it helps you!

Thursday, October 8, 2009

WITH SCHEMABINDING Clause in SQL Server

In My Previous post (View in SQL Server), I’ve mentioned that a table can be deleted even though it is associated with normal view. Also we can modify that table design or drop that table without any notification or warning message.

Have a look at this simple scenario,

Here I’ve a table, Named as Employee with 3 columns Empno, Empname, Test.



I created a view with following definition,


CREATE VIEW ViewTest
AS
SELECT Empno,EmpName FROM dbo.Employee
GO
 

After created the view "ViewTest", I renaming the column EmpName to Empname2

Now If we access the views, after modified the schema of the base table, it will throw the error like

Msg 207, Level 16, State 1, Procedure ViewTest, Line 3
Invalid column name 'EmpName'.
Msg 4413, Level 16, State 1, Line 1
Could not use view or function 'ViewTest' because of binding errors.
 

Also it allows me the drop the base table.

DROP TABLE Employee
GO
 

If we access the views, after drop the base table, it will throw the error like
Msg 208, Level 16, State 1, Procedure ViewTest, Line 3
Invalid object name 'dbo.Employee'.
Msg 4413, Level 16, State 1, Line 1
Could not use view or function 'ViewTest' because of binding errors.



To avoid this sort of issues, SQL Server provided a option called SCHEMABINDING. This option will bind the table and schema together, also it is restricting the schema changes against on the base table. So we can avoid the error.


The following snippet helps, how to make a view with SCHEMABINDING

CREATE VIEW ViewTest WITH SCHEMABINDING
AS
SELECT Empno,EmpName FROM dbo.Employee
GO

Now if you try to change the column name of base table, then it will throw the following error

'Employee' table
- Warning: The following schema-bound objects will be modified:
  - View 'dbo.ViewTest': schema binding will be removed.


If you want to enforce the SCHEMABINDING  to existing view, you can follow the snippet given below

ALTER VIEW ViewTest WITH SCHEMABINDING
AS
SELECT Empno,EmpName FROM dbo.Employee
GO


Hope it helps you!

View in SQL Server

What is View in SQL?

  • View is a virtual table.
  • it won’t occupies any memory space for the data.
  • it is referencing to the other table like pointer concept in programming language.
  • View definition contains only SELECT statement.
  • Views simplify the user perception of the database
  • View improves the data security by preventing undesired access
  • View faciliates the provision of additional data independence
  • View doesn’t allow ORDER BY clause in view definition.
Can You Drop a table, If it has a view?

If the view is created with SCHEMABINDING clause from Table or views then base object can’t delete otherwise you can.

Why SQL Server Doesn’t allow ORDER BY Clause in View definition?
SQL Server excludes an ORDER BY clause from a view to comply with the ANSI SQL-92 standard. Because analyzing the rationale for this standard requires a discussion of the underlying structure of the structured query language (SQL) and the mathematics upon which it is based, also if you use the ORDER BY Clause then it will lead to major performance issue, sothat by default SQL server doesn’t allow this clause in view definition.

If you try to create view with ORDER BY clause it will throw the following error.
Msg 1033, Level 15, State 1, Procedure , Line 2
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.



Wednesday, October 7, 2009

Try... Catch... Error Handling in SQL 2005


Recently I’ve posted about the topic Handling Error in SQL, in this link, I’ve explained, what is the simplest way to handle the error?  This can be implemented in all version of SQL Server.

In SQL Server 2005 offers major improvements in error handling inside T-SQL transactions. Now you can use Try… Catch Block in SQL Transactions Which is available in Programming languages Like C#, VB.NET..,
 

You can now catch -SQL and transaction abort errors using the TRY/CATCH model without any loss of the transaction context. 

The syntax is shown here:
BEGIN TRY
sql statement
END TRY
BEGIN CATCH TRAN_ABORT
    --sql statement for catching your errors
END CATCH


This will be functioning the same way of Try… Catch in Programming language.
If an error within an explicit transaction occurs inside a TRY block, control is passed to the CATCH block that immediately follows. If no error occurs, the CATCH block is completely skipped.

You can investigate the type of error that was raised and react accordingly. To do so, you can use the new ERROR functions to return error information in the CATCH block, as shown here:


BEGIN TRY
   SELECT 5/0
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;
END CATCH

 You can examine the value of the ERROR functions to decide what to do with the control flow of your procedure and whether to abort any transactions. When you experience a transaction abort error inside a transaction located in the TRY block, control is passed to the CATCH block. The transaction then enters a failed state in which locks are not released and persisted work is not reversed until you explicitly issue a ROLLBACK statement. You're not allowed to initiate any activity that requires opening an implicit or explicit transaction until you issue a ROLLBACK
Sometimes certain types of errors are not detected by the TRY/CATCH block, and you end up with an unhandled exception even though the error occurred inside your TRY block. If this happens, the CATCH block is not executed. This is because CATCH blocks are invoked by errors that take place in actual executing code, not by compile or syntax errors. Two examples of such errors are syntax errors and statement-level recompile errors (for example, selecting from a nonexistent table). These errors are not caught at the same execution level as the TRY block, but at the lower level of executionwhen you execute dynamic SQL or when you call a stored procedure from the TRY block. For example, if you have a syntax error inside a TRY block, you get a compile error and your CATCH block will not run:




-- Syntax error doesn't get caught
BEGIN TRY
   SELECT * * FROM XYX
END TRY
BEGIN CATCH
   PRINT  'Error'
END CATCH
GO

 

The result is an error from SQL Server, not from your CATCH block:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '*'.



Statement-level recompilation errors don't get caught by CATCH blocks, either. For example, using a nonexistent object in a SELECT statement in the TRY block forces an error from SQL Server, but your CATCH block will not execute:

-- Statement level recompilation doesn't get caught
-- Example - nonexistent object


BEGIN TRY
   SELECT * FROM XYX
END TRY
BEGIN CATCH
   PRINT 'Error'
END CATCH
GO


The result is an error from SQL Server: 

Msg 208, Level 16, State 1, Line 2
Invalid object name 'XYX'.


Error Handling in SQL

How will you handle Errors in Sql Stored Procedure?

SQL Provides a system variable named as @@ERROR, If any error occured in query execution, then error code will be set to @@ERROR, if there is no error, by default it holds the 0 value. so based on this value we can handle the error in SQL

INSERT dbo.emp VALUES (@Column2)

IF @@ERROR <>0
BEGIN
PRINT 'Error Occured'
END

The given code will print the following error

Msg 137, Level 15, State 2, Line 1

Must declare the scalar variable "@Column2".

For further info about this variable, have a look at the following link

http://msdn.microsoft.com/en-us/library/aa933181(SQL.80).aspx

How will you raise an error in sql?
RAISERROR - Returns a user-defined error message and sets a system flag to record that an error has occurred. Using RAISERROR, the client can either retrieve an entry from the sysmessages table or build a message dynamically with user-specified severity and state information. After the message is defined it is sent back to the client as a server error message.

Refer RAISERROR

Thursday, October 1, 2009

Stored Procedure And Its Types - SQL


A stored procedure is a set of Structured Query Language (SQL) statements that you assign a name to and store in a database in compiled form so that you can share it between a number of programs.

    * They allow modular programming.
    * They allow faster execution.
    * They can reduce network traffic.
    * They can be used as a security mechanism.

SP are classified as Following Types:

    * Temporary Stored Procedures
    * System stored procedures 
    * Automatically Executing Stored Procedures
    * User stored procedure

Temporary Stored Procedures:
SQL Server supports two types of temporary procedures:local and global.

A local temporary procedure is visible only to the connection that created it.

A global temporary procedure is available to all connections. Local temporary procedures are automatically dropped at the end of the current session. Global temporary procedures are dropped at the end of the last session using the procedure. Usually, this is when the session that created the procedure ends. Temporary procedures named with # and ## can be created by any user.

System stored procedures are created and stored in the master database and have the sp_ prefix.(or xp_) System stored procedures can be executed from any database without having to qualify the stored procedure name fully using the database name master. (If any user-created stored procedure has the same name as a system stored procedure, the user-created stored procedure will never be executed.)

Automatically Executing Stored Procedures - One or more stored procedures can execute automatically when SQL Server starts. The stored procedures must be created by the system administrator and executed under the sysadmin fixed server role as a background process. The procedure(s) cannot have any input parameters.

User stored procedure:

It is a Normal Procedure which are all written by user. It will be available in the User Database.

Thursday, September 24, 2009

What is Index in SQL?

Indexes in DB are very similar to indexes in the books. It helps to search the data very quickly without scanning whole data in a table. Index can be defined on either single column or multiple columns of a table. index will arrange the data in specific manner . Index is an data structure that improves the operation of a table.

There are many classification of index in SQL, the following Indexes are most often used by everyone, which are as Clustered, Non-Clustered and Unique Index.

Clustered:

A clustered index sorts and stores the data rows of the table or view in order based on the clustered index key. The clustered index is implemented as a B-tree index structure that supports fast retrieval of the rows, based on their clustered index key values.

Every table can have only one clustered index.

Nonclustered:

A Nonclustered index can be defined on a table or view with a clustered index or on a heap. Each index row in the Nonclustered index contains the Nonclustered key value and a row locator. This locator points to the data row in the clustered index or heap having the key value. The rows in the index are stored in the order of the index key values, but the data rows are not guaranteed to be in any particular order unless a clustered index is created on the table.

Every table can have maximum of 249 Nonclustered index.

Unique:

A unique index ensures that the index key contains no duplicate values and therefore every row in the table or view is in some way unique.

Both clustered and nonclustered indexes can be unique.