Category Archives: SQL

Fix: BEGIN TRY does not work with BULK INSERT on SQL

I have created a stored procedure that does a BULK IMPORT. I wanted to add a bit of fault checking and added a BEGIN TRY and a BEGIN CATCH so that it sends an email with the error message if the T-SQL fails. The problem is that the BEGIN CATCH was being skipped and the procedure stops processing with the below error message.

Msg 4860, Level 16, State 1, Line 2
Cannot bulk load. The file "C:\temp\fileimport.txt" does not exist.

To fix the issue what I did is to add the BULK INSERT command in a variable and execute it. This way, the BEGIN CATCH is not ignored or skipped.

Fix below

BEGIN TRY
DECLARE @bulkimport varchar(1000)
SET @bulkimport = 'BULK INSERT mytable FROM ''C:\temp\fileimport.txt''
WITH (FIELDTERMINATOR = ''*'', ROWTERMINATOR = ''\n'')'
EXECUTE (@bulkimport)
END TRY

BEGIN CATCH
SELECT error_message()
END CATCH

(74)

How to: Execute DOS commands from T-SQL

Sometimes you might have the need to execute a copy, delete or run a batch file from a stored procedure. This can be done by using the xp_cmdshell and execute your command line.

This can be done as below

EXECUTE master..xp_cmdshell 'copy c:\test.txt c:\test1.txt'

You can run it using parameters as below

DECLARE @sql VARCHAR(200)
SET @sql = 'copy c:\test.txt c:\test1.txt'
EXECUTE master..xp_cmdshell @sql

If you are running the xp_cmdshell and get the error "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." Follow the code below to enable the feature.

EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'xp_cmdshell', 1;
GO
RECONFIGURE;
GO

(63)

Fix: The backup set holds a backup of a database other than the existing

When restoring a database from an SQL backup .bak, one usually creates a database and then selects the restore function. As soon as you try to restore the database you get the error saying “The backup set holds a backup of a database other than the existing“. This is because it fails to read the files from the restore and matching them to the newly created files.

The error says:

Restore failed for Server ‘SQLSRV01’. (Microsoft.SqlServer.SmoExtended)
Additional Information
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
The backup set hold a backup of a database other an the existing ‘test_restore’ database.
RESTORE DATABASE is terminating abnormally. (Microsoft SQL Server, Error: 3154)

To solve this one should do the following:

– Don’t create an empty database and restore the .bak file on to it.
– Use ‘Restore Database’ option accessible by right clicking the “Databases” branch of the SQL Server Management Studio and provide the database name while providing the source to restore.

This should allow you to restore the database with no error and fix the error 3154.

(1183)

Fix: The In-row data page count for object is incorrect when running integrity check on SQL

When running an integrity check on your databases, you may get the following error on some databases.

Description: Executing the query "DBCC CHECKDB(N'mydb')  WITH NO_INFOMSGS  " failed with the following error: "The In-row data myrow page count for object "my_table", index ID 0, partition ID 52794353778688, alloc unit ID 52794353778688 (type In-row data) is incorrect.

This is due to the fact that the database in question was imported from another or older version of your current SQL server. This can be fixed by running the below command on the databases in question.

DBCC UPDATEUSAGE (dbname)

dbname = The name of your database

When the database is indeed one which is failing the integrity check you will see the below sample message.

DBCC UPDATEUSAGE: Usage counts updated for table 'mytable' (index 'mytable', partition 1):
DATA pages (In-row Data): changed from (2) to (1) pages.
USED pages (In-row Data): changed from (25) to (24) pages.
RSVD pages (In-row Data): changed from (41) to (40) pages

If the database doesn’t need to update it’s usage you will simply get the message below.

DBCC execution completed.

Once you have executed the update-usage on all databases which are failing, run the integrity check again and swish, it works.

 

 

(4747)

Fix: SQL Server Database Services feature state failed during upgrade

During an SQL version upgrade I have encountered that during the checkup, you will get the error stating that Database Services feature state failed. This can be fixed by finding the registry entry below and changing as follows.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.\ConfigurationState.

Change all values from 2 to 1 for all Four items in the right pane.

Re-Run the rule on the installation. Now it will be solved and through.

(2719)

Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405

When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this,
Open SQL Management Studio and Click New Query. Type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database.

(34100)

How to: Get all the information regarding your SQL server installed

When running the following script, will get you a verbose of the SQL server installed. This will get you the Service Pack number, version and other information which includes Product Level and other interesting stuff.

Note: if you would like to get a simplified information on the SQL server simply run the SELECT @@VERSION on your SQL while using the Master database, but if you want to know more in detail, use the script below.

SELECT @@VERSION
GO

SELECT SERVERPROPERTY('ProductVersion') 'Version', SERVERPROPERTY ('ProductLevel') 'Service Pack', SERVERPROPERTY ('Edition') 'Edition'
GO

-- Stored procedure, documented in Books Online, that returns numerous key / value pairs including version information.
-- There doesn't seem to be a correlation between the key names here and SERVERPROPERTY values;
-- for example, 'ProductVersion' is returned by xp_msver, but 'ProductLevel' is not.
xp_msver
GO

-- Stored procedure, documented in Books Online, that returns numerous key / value pairs including version information.
-- For SQL Server 2008, DBMS_VER returns "Microsoft SQL Server Yukon - 10.0.1600".
sp_server_info
GO

-- Stored procedure, not documented in Books Online, that returns the version string.
sp_MSgetversion
GO

-- @@MicrosoftVersion returns a decimal value which, when converted to varbinary, yields (for example) 0x09000FC3.
-- Enter "convert 0x0FC3 to decimal" in Google, and the result is 4035. Thus the overall MicrosoftVersion is 09.00.4035.
SELECT CONVERT(VARBINARY, @@MicrosoftVersion)
GO

-- get version info from the registry (SQL 2005 key names - keys may vary)
xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\Setup\', @value_name='Version'
GO
xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\Setup\', @value_name='Edition'
GO
xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\Setup\', @value_name='SP'
GO

-- get version info from the registry (SQL 2008 key names - keys may vary)
xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\Setup\', @value_name='Version'
GO
xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\Setup\', @value_name='Edition'
GO
xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\Setup\', @value_name='SP'
GO

(596)

How to: Find users in SQL having DB Owner role

Find members of db_owners in all databasesThis script is aim to provide all members of the db_owner database role in all databases in an instance. It
The following code returns the role name and the member name filtered for the db_owner database

This script is aim to provide all members of the db_owner database role in all databases in an instance. It uses sp_MSForEachDb with a custom script using sys.database_principals DMV. The following code returns the role name and the member name filtered for the db_owner database role.

exec sp_msForEachDb ' use [?]
select db_name() as [database_name], r.[name] as [role], p.[name] as [member] from
sys.database_role_members m
join
sys.database_principals r on m.role_principal_id = r.principal_id
join
sys.database_principals p on m.member_principal_id = p.principal_id
where
r.name = ''db_owner'''

(653)

How to: Execute SQL stored procedures using command line

Often when having SQL Express Editions installation I would like to schedule and execute stored procedures. Using Express editions you cannot make use of the SQL Agent, but you can run them manually using a batch file and using the SQLCMD.EXE file as below

SQLCMD /Q "USE mydb; EXEC mystoredprocedure"

This will use the mydb that you specify and run the mystoredprocedure. You can also use the > filename.txt to make the job log.

(628)