Restore SQL Server 2012 backup to a SQL Server 2008 database

You have couple of options :

Option A : Script out database in compatibility mode using Generate script option :

Note : If you script out database with schema and data, depending on your data size, the script will be massive and wont be handled by SSMS, sqlcmd or osql (might be in GB as well).


Option B:

First script out tables first with all Indexes, FK’s, etc and create blank tables in the destination database – option with SCHEMA ONLY (No data).

Use BCP to insert data

  1. bcp out the data using below script. set SSMS in Text Mode and copy the output generated by below script in a bat file.
    -- save below output in a bat file by executing below in SSMS in TEXT mode
    -- clean up: create a bat file with this command --> del D:\BCP\*.dat 
    select '"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp.exe" ' /* path to BCP.exe */
        +  QUOTENAME(DB_NAME())+ '.' /* Current Database */
        +  QUOTENAME(SCHEMA_NAME(SCHEMA_ID))+'.'            
        +  QUOTENAME(name)  
        +  ' out D:\BCP\'  /* Path where BCP out files will be stored */
        +  REPLACE(SCHEMA_NAME(schema_id),' ','') + '_' 
        +  REPLACE(name,' ','') 
        + '.dat -T -E -SServerName\Instance -n' /* ServerName, -E will take care of Identity, -n is for Native Format */
    from sys.tables
    where is_ms_shipped = 0 and name <> 'sysdiagrams'                       /* sysdiagrams is classified my MS as UserTable and we dont want it */
    /*and schema_name(schema_id) <> 'unwantedschema'    */                             /* Optional to exclude any schema  */
    order by schema_name(schema_id)
  2. Run the bat file that will generate the .dat files in the folder that you have specified.
  3. Run below script on the destination server with SSMS in text mode again.
    --- Execute this on the destination server.database from SSMS.
    --- Make sure the change the @Destdbname and the bcp out path as per your environment.
    declare @Destdbname sysname
    set @Destdbname = 'destinationDB' /* Destination Database Name where you want to Bulk Insert in */
    select 'BULK INSERT ' 
    /*Remember Tables must be present on destination database */ 
    + QUOTENAME(@Destdbname) + '.' 
    + '.' + QUOTENAME(name) 
    + ' from ''D:\BCP\' /* Change here for bcp out path */ 
    + REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '') 
    + '.dat'' with ( KEEPIDENTITY, DATAFILETYPE = ''native'', TABLOCK )' 
    + char(10) 
    + 'print ''Bulk insert for ' + REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '') + ' is done... ''' 
    + char(10) + 'go'
       from sys.tables
       where is_ms_shipped = 0
    and name <> 'sysdiagrams' /* sysdiagrams is classified my MS as UserTable and we dont want it */
    and schema_name(schema_id) <> 'unwantedschema' /* Optional to exclude any schema */
        order by schema_name(schema_id) 
  4. Run the output using SSMS to insert data back in the tables.

This is very fast bcp method as it uses Native mode.

How do I generate insert statements/ script (including data) with Sql server 2012

  • Right click on your database and select Tasks -> Generate Scripts
  • Click Next to move past the intro screen and onto the next page, then select the objects you want to script. Note that you can script all SQL objects here, not just tables. This is because this wizard allows you to script schema and data. Importantly, schema only is the default, which you’ll need to change on the next page. Click Next.
  • Now you’ll be presented with a set of options mainly relating to how the script is going to be output, however there is an unassuming button labelled Advanced. Clicking this button will give you a dialog with a list of options. The last option under the General section is “Types of data to script”, which you should change from “Schema only” to “Data only”, or “Schema and data”.
  • Finally, decide where you want the script to do and you should be able to generate your INSERT statements.


Generating INSERT statements in SQL Server 2012

Recently, I wrote an article on “Generating Insert statements, data & schema using SQL Server Publishing Wizard”. It is a very nice tool to generate insert into statement from table data.

In SQL server 2012, the feature of this tool plus additional features are provided. Lets proceed step by step to generate insert into statement from table data in SQL server 2012.

Step 1 :

In the first step, you need to right click on Databases >> Tasks >> Generate Scripts…

Step 2 :

This is the welcome screen. If you don’t need this screen again and again you can check on “Do not show this page again”.

Step 3 :

In this step, you need to generate the script for one object or all objects available in the database. You can further drill down if you need to generate any table. For example :

Setup 4 :

The next step is to define the script location, clip board or in a new window. In the same step, if you click on Advanced button, it will give you further control on scripting.

This is the advance screen, in this screen you can choose whether you need data, schema or data and schema scripts.’

But if you need only Insert into statement from table data, you must select data only. By default it is schema only.

It also allows you to select the SQL version.

Step 5 :

In this step it will display the summary of your selection. If you need you can go back and change the settings.

Step 6 :

In this step, it will display the result.


SQL Server: SELECT TOP Statement (TOP n th Position) by using WITH TIES

FROM [Hall_Info].[dbo].[ug_applicant_general_info]

[Curtsy] Original Post:

SQL Server: SELECT TOP Statement

This SQL Server tutorial explains how to use the SELECT TOP statement in SQL Server (Transact-SQL) with syntax and examples.


The SQL Server (Transact-SQL) SELECT TOP statement is used to retrieve records from one or more tables in SQL Server and limit the number of records returned based on a fixed value or percentage.


The syntax for the SELECT TOP statement in SQL Server (Transact-SQL) is:

SELECT TOP (top_value) [ PERCENT ] [ WITH TIES ]
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]];

Parameters or Arguments

TOP (top_value)
Returns the top number of rows in the result set based on top_value. For example, TOP(10) would return the top 10 rows from the full result set.
Optional. If PERCENT is specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value). For example, TOP(10) PERCENT would return the top 10% of the full result set.
Optional. If the WITH TIES clause is specified, then rows tied in last place within the limited result set are returned. This may result in more rows be returned than the TOP parameter permits.
The columns or calculations that you wish to retrieve.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
ORDER BY expression
Optional. It is used in the SELECT TOP statement so that you can order the results and target those records that you wish to return. ASC is ascending order and DESC is descending order.

Example – Using TOP keyword

Let’s look at a SQL Server example, where we use the TOP keyword in the SELECT statement.

For example:

employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY employee_id;

This SQL Server SELECT TOP example would select the first 5 records from the employees table where the last_name is ‘Anderson’. If there are other records in the employees table that have a last_name of ‘Anderson’, they will not be returned by the SELECT statement.

You could modify this example to include the WITH TIES clause as follows:

employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY employee_id;

The WITH TIES clause would include rows that may be tied in last place within the limited result set. So if the 5th top record is a tie, then all records in this tie position would be returned by the SELECT TOP statement. This will result in more than 5 records being returned.

Example – Using TOP PERCENT keyword

Let’s look at a SQL Server example, where we use the TOP PERCENT keyword in the SELECT statement.

For example:

employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY employee_id;

This SQL Server SELECT TOP example would select the first 10% of the records from the full result set. So in this example, the SELECT statement would return the top 10% of records from the employees table where the last_name is ‘Anderson’. The other 90% of the result set would not be returned by the SELECT statement.

You could modify this example to include the WITH TIES clause as follows:

employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY employee_id;

The WITH TIES clause would include rows that may be tied in last place within the limited result set. So if the last position in the SELECT TOP(10) PERCENT record set is a tie, then these tied records would be returned by the SELECT TOP statement. This will result in more than 10% of the full record set being returned.


Finding Duplicate Records Using GROUP BY in SQL Server

Original Post:

There are various times when we need to find duplicate records in SQL Server. It is possible to find duplicates using DISTINCT, ROW NUMBER as well as the GROUP BY approach.

Duplicate records can create problems sometimes when displaying reports or performing a Multiple Insert update. Finding duplicate records in a database needs further investigation. In some cases, duplicate records are positive, but it all depends on the data and the database design as well.

For example, if a customer has ordered the same product twice on the same date with the the same shipping and billing address, then this may result in a duplicate record.

Let us create a table Customer with First Name, Last Name, and Mobile Number fields.

FirstName VARCHAR(50),
LastName  VARCHAR(50),
MobileNo  VARCHAR(15)

INSERT INTO CUSTOMER VALUES ('Niraj','Yadav',989898);

INSERT INTO CUSTOMER VALUES ('Chetan','Gadodia',959595);
INSERT INTO CUSTOMER VALUES ('Chetan','Gadodia',959595);

INSERT INTO CUSTOMER VALUES ('Atul','Kokam',42424242);
INSERT INTO CUSTOMER VALUES ('Atul','Kokam',42424242);

INSERT INTO CUSTOMER VALUES ('Vishal','Parte',9394453);
INSERT INTO CUSTOMER VALUES ('Vishal','Parte',9394453);
INSERT INTO CUSTOMER VALUES ('Vishal','Parte',9394453);

INSERT INTO CUSTOMER VALUES ('Jinendra','Jain',121212);
INSERT INTO CUSTOMER VALUES ('Jinendra','Jain',121212);


Finding Duplicates Records Using Group by in SQL Server (2)

Using the DISTINCT approach, we can quickly get unique rows in a table.


Finding Duplicates Records Using Group by in SQL Server (3)

However, this does not show how many times a row has been duplicated. Using the GROUP BY approach, we can find this.

Finding Duplicates Using GROUP BY

Adding grouping and a counting field to our display of FirstName, LastName and MobileNo combination shows how many times each customer’s name appears.

SELECT		FirstName, LastName, MobileNo, COUNT(1) as CNT
GROUP BY	FirstName, LastName, MobileNo;

Finding Duplicates Records Using Group by in SQL Server (4)

GROUP BY will show just one record for each combination of FirstName, LastName and MobileNo.

The count CNT shows how many times the row has been duplicated.
CNT = 1 indicates that row appears only once.

Let us filter out using the Having clause to exclude rows that appear only once.

SELECT		FirstName, LastName, MobileNo, COUNT(1) as CNT
GROUP BY	FirstName, LastName, MobileNo

Finding Duplicates Records Using Group by in SQL Server (1)

How to update data in one table from corresponding data in another table in SQL Server


update t2
set t2.deptid = t1.deptid
from test1 t1, test2 t2
where t2.employeeid = t1.employeeid


USE [UG_AdmissionDb]
-- exec sp_BackupData

ALTER PROCEDURE [dbo].[sp_Modified_Data]
    -- Begin Trnsaction
        BEGIN TRANSACTION        
            UPDATE t2
            SET t2.[BANGLA] = t1.BANGLA,
            t2.[ENGLISH] = t1.[ENGLISH],
            t2.[PHYSICS] = t1.[PHYSICS],
            t2.[CHEMISTRY] = t1.[CHEMISTRY],
            t2.[MATHEMATICS] = t1.[MATHEMATICS],
            t2.[BIOLOGY] = t1.[BIOLOGY],
            t2.[SUB_4TH] = t1.[SUB_4TH],
            t2.[GPA] = t1.[GPA],
            t2.[CGPA] = t1.[CGPA],
            t2.[LTGRADE] = t1.[LTGRADE]

            FROM [ReScrutiny].[dbo].[ug_data_full_board_hsc] as t1, [UG_AdmissionDb].[dbo].[ug_data_full_board_hsc]  as t2
              t2.[ROLL] = t1.[ROLL]
              AND t2.[REG] = t1.[REG]
              AND t2.[PASSYEAR] = t1.[PASSYEAR]
              AND t2.[BOARDNAME] = t1.[BOARDNAME]
        select 'Process Successful!' IsOk
        IF(@@TRANCOUNT > 0)
        select ERROR_MESSAGE() IsOk    

MySQL to SQL Server Migration: How to Microsoft SQL Server Migration Assistant (SSMA)

In this blog, I’m going to walk you through the process of converting the MySQL Sakila-DB sample database to SQL Server 2008 R2 Express using the SQL Server Migration Assistant for MySQL v1.0 [Updated:  Please obtain the lastest SSMA for MySQL] (SSMA). The Sakila-DB database has tables, views, stored procedures, functions and triggers that make the conversion interesting. The sample is based on the Inno-DB example, but does have one MyISAM table. SSMA also allows you to migrate your MySQL databases to SQL Azure, but we’ll save that topic for another post.

Downloading SQL Server 2008 R2 Express and SSMA

The easiest way to download SQL Server 2008 R2 Express, SQL Server Management Studio and SSMA is through the Microsoft Web Platform Installer (WPI). Once you’ve downloaded WPI, you can select from a variety of tools and products that can get you up and running using IIS, PHP, and SQL Server in no time.

00 Web Platform Installer

I’ll focus on the minimum set of tools you need to get SQL Server 2008 R2 Express and SSMA up and running. once you launch WPI, click on the Products tab at the top tool and then select Database in the navigation page. In the image above, I’ve already installed the tools, but for the new install, you’ll click on the Add buttons to the right of the circled products to get you up and running. If you are running your application under PHP, you might also want to select one of the two PHP drivers for SQL Server as well. Once you’ve selected your tools, just click on the install button to start the process.

Downloading the MySQL ODBC Driver

WPI is not without flaws. SSMA requires the “MySQL OSBC Driver 5.1 or above” download to connect to your MySQL instance that comes from the MySQL downloads site. Once at the Download Connector/ODBC page, your need to download either the x32 or x64 version of the driver based on the machine architecture for the system you are running the SSMA client. Just follow the installation instructions from the installer. The default installation settings will be good enough to get you going.

Other Helpful Downloads for SSMA and this Blog

You’ll also want to download the “Guide to Migrating from MySQL to SQL Server 2008” white paper, though this blog and others to follow will keep you on track.

If you don’t already have the Sakila-DB database for MySQL installed, the link to the download and instructions for installing it can be found at the blog post titled “Learn MySQL With Sakila sample Mysql Database

Using SSMA for MySQL

SQL Server Migration Assistant (SSMA) 2008 for MySQL lets you quickly convert MySQL database schemas to SQL Server 2008, SQL Server 2008 R2 or SQL Azure schemas, upload the resulting schemas the target instance and migrate the data using a single tool.

Licensing SSMA

SSMA is a free tool, but does require you to associate a Microsoft Live ID for identification purposes. You must download a registration key. To help you with the registration process, a License Key Required dialog box opens the first time that you start the SSMA program. Use the following instructions to download a license key and associate the key with SSMA.

To license SSMA

  1. Click Start, point to All Programs, point to Microsoft SQL Server Migration Assistant 2008 for MySQL, and then select Microsoft SQL Server Migration Assistant 2008 for MySQL.
  2. In the License Management dialog box, click the license registration page link.
  3. On the Sign In Web page, enter your Windows Live ID user name and password, and click Sign In.

    A Windows Live ID is a Hotmail e-mail address, MSN e-mail address, or Microsoft Passport account. If you do not have one of these accounts, you will have to create a new account. To create a new account, click the Sign up now button.

  4. On the SQL Server Migration Assistant for MySQL License Registration Web page, fill in at least the required fields, which are marked with a red asterisk, and then click Finish.
  5. In the File Download dialog box, click Save.
  6. In the Save As dialog box, locate the folder that is shown in the License Management dialog box, and then click Save.

    The default location is C:\Documents and Settings\user name\Application Data\Microsoft SQL Server Migration Assistant\m2ss.

  7. In the License Management dialog box, click Refresh License.

SSMA for MySQL User Interface

After SSMA is installed and licensed, you can use SSMA to migrate MySQL databases to SQL Server 2008 or SQL Azure. It helps to become familiar with the SSMA user interface before you start. The following diagram shows the user interface for SSMA, including the metadata explorers, metadata, toolbars, output pane, and error list pane:

01 SSMA MySQL UI OverviewS

Basic Steps for Migration of MySQL to SQL Server

To start a migration, you’ll need to perform the following high level steps:

  1. Create a new project.
  2. Connect to a MySQL database.
  3. After a successful connection, MySQL schemas will appear in MySQL Metadata Explorer. Right-click objects in MySQL Metadata Explorer to perform tasks such as create reports that assess conversions to SQL Server 2008 R2 Express. You can also perform these tasks by using the toolbars and menus.

You’ll then connect to your instance of SQL Server 2008 R2 Express. After a successful connection, a hierarchy of your existing databases will appear in SQL Server Metadata Explorer. After you convert MySQL schemas to SQL Server schemas, select those converted schemas in SQL Server Metadata Explorer, and then synchronize the schemas with SQL Server.

After you synchronize converted schemas with SQL Server 2008 R2 Express, you can return to MySQL Metadata Explorer and migrate data from MySQL schemas into target database.

Let’s walk through the specifics.

Create a MySQL Migration Project

To get started, you’ll create your new project using the File | New Project command.

02 Create Project

You’ll enter in your project name and then confirm that you are migrating to SQL Server. The Migrate To dropdown also allows you to choose SQL Azure, but that’s for another post. Once you make your selection, you are locked into the target backend.

Connect to a MySQL Database

To Connect to your MySQL instance, you’ll issue the File | Connect to MySQL command or click on the tool bar button that launches the following dialog:

03 Connect to MySQL

If you forgot to to install the MySQL ODBC driver mentioned at the beginning of this blog, simply go to the download site, install the driver, and then issue the Connect to MySQL command.

Create Report of Potential Conversion Issues

Once you are connected, you’ll see the MySQL instance in the MySQL Metadata Explorer. You’ll want to expand the Databases node along with the Sakila database node and then check the box next to Sakila. This selects the database you want to migrate. Next, right click on the Sakila database and select the Create Report command or press the Create Report command on the toolbar as shown below.

04 Create Report

Here is an example of the Assessment Report for the Sakila database.

05 Assessment Report

The Assessment Report window contains three panes:

  • The left pane contains the hierarchy of objects that are included in the assessment report. You can browse the hierarchy, and select objects and categories of objects to view conversion statistics and code.
  • The content of the right pane depends on the item that is selected in the left pane.

    If a group of objects is selected, such as schema, the right pane contains a Conversion statistics pane and Objects by Categories pane. The Conversion Statistics pane shows the conversion statistics for the selected objects. The Objects by Categories pane shows the conversion statistics for the object or categories of objects.

    If a function, procedure, table or view is selected, the right pane contains statistics, source code, and target code.

    • The top area shows the overall statistics for the object. You might have to expand Statistics to view this information.
    • The Source area shows the source code of the object that is selected in the left pane. The highlighted areas show problematic source code.
    • The Target area shows the converted code. Red text shows problematic code and error messages.
  • The bottom pane shows conversion messages, grouped by message number. You can click Errors, Warnings, or Info to view categories of messages, and then expand a group of messages. Click an individual message to select the object in the left pane and display the details in the right pane.

In future blog posts, we’ll work through the specific problems that are in this report. For now, we’ll ignore the problematic objects for the schema and data migration steps. For now, close the report and then uncheck Functions, Procedures and Views nodes to take them out of the conversion. Then uncheck the tables with errors as shown below.

06 Ignore Errors

Go ahead and click on the Create Reports command to verify that there are no errors.

Connect to SQL Server

It’s time to connect SSMA to your SQL Server 2008 R2 Express instance. For the Server name, you’ll need the server name and instance for the target server. Since we are using the WPI installation of SQL Server 2008 R2 Express, you’ll enter in the server name as .\SQLEXPRESS.

You can select an existing database to migrate to using the Database control. You can also type in the name of a new database. In this case, use Sakila as shown below.

07 Connect to SQL Server

Once you click connect, SSMA prompts you if you want to create the database. Choose Yes to create the new database. When connecting to SQL Server Express instances, you’ll receive the following warning indicating that you won’t be able to use the server-side data migration engine. This engine is used for larger migration projects.

08 No SQL Agent

You can Continue from this dialog to start the actual migration process.

Convert Schema

Now that you’ve connected to the target SQL Server instance, SSMA enables the Convert Schema command. Click the Convert Schema command. Once the conversion is finished, you should see the SQL Server Metadata Explorer populated with the tables listed in bold as shown below.

09 Convert schema

Synchronize with Database

To write the tables to the target, select the dbo node in the SQL Server Metadata Explorer and then issue the Tools | Synchronize with Database command. SSMA displays the Synchronize with Database dialog as shown below. In this example, the Tables node was manually expanded to show that no tables are actually on the database at this time.

10 Sync with database

When you click OK, SSMA issues the CREATE TABLE statements to create the objects on the SQL Server target. There are some errors in this example because many of the tables selected have foreign key relationships to some of the tables that we excluded earlier. These errors can be ignored for now.

Migrate Data

The last step is to migrate the data into the tables. To complete the migration, select the Tables node within the MySQL Metadata Explorer for the Sakila database. Then issue the Tools | Migrate Data command or press the command on the toolbar. The Data Migration process requires you to connect to the MySQL database and to the SQL Server database again. SSMA then proceeds with the data migration process and displays the Data Migration Reports as shown below.

11 Migrate Data

Using SQL Server Management Studio

The migrated tables are now ready on the target SQL Server instance. To see the results, launch SQL Server Management Studio (SSMS) and connect using the server name as .\SQLEXPRESS. Expand out the Databases node to see the Sakila database. Expand the out the Sakila database tables and then right click on the actor table and issue the Select Top 1000 Rows command to view the data as shown below.

12 Verifying the results

SQL Server Management Studio that is part of the WPI is a free rich Windows client tool from Microsoft that offers a rich development and management experience like  SQLyog and MONyog.

database ‘msdb’ cannot be opened. it has been marked suspect by recovery 2008 error code 926

Problem:  I have got this problem in local instance of SQL Server 2008 R2 on my machine. There are several databases on this instance. But I am not able to see any of them from the object explorer.

I am able to query my databases from the new query window. But not able to see any of them.

Whenever I try to explore the databases I get this error :

Database ‘msdb’ cannot be opened. It has been marked SUSPECT by recovery. See the SQL Server errorlog for more information. (Microsoft SQL Server, Error: 926).

I have tried

  1. Refreshing the connection
  2. Reconnecting the connection
  3. Restarting the service Sql Server (MSSQLSERVER).
  4. Restarting the SQL Server Management Studio
  5. Restarting my machine

I have also tried combinations of above, but nothing works.

My operating system is Windows 7 Ultimate (64 bit).

SQL Server Management Studio Version is 10.50.2500.0.

Solution 1

  1. Open new query window
  2. EXEC sp_resetstatus 'DB_Name'; (Explanation :sp_resetstatus turns off the suspect flag on a database. This procedure updates the mode and status columns of the named database in sys.databases. Also note that only logins having sysadmin privileges can perform this.)
  3. ALTER DATABASE DB_Name SET EMERGENCY; (Explanation : Once the database is set to EMERGENCY mode it becomes a READ_ONLY copy and only members of sysadmin fixed server roles have privileges to access it.)
  4. DBCC checkdb('DB_Name'); (Explanation : Check the integrity among all the objects.)
  5. ALTER DATABASE DB_Name SET SINGLE_USER WITH ROLLBACK IMMEDIATE; (Explanation : Set the database to single user mode.)
  6. DBCC CheckDB ('DB_Name', REPAIR_ALLOW_DATA_LOSS); (Explanation : Repair the errors)
  7. ALTER DATABASE DB_Name SET MULTI_USERDetails; (Explanation : Set the database to multi user mode, so that it can now be accessed by others.)

Solution 2

  1. In Object Explorer –> The opened connection item –> rightclick –> Stop Object Explorer
  2. Open Control Panel –> Administrative Tools –> Services Control Panel -> Administrative Tools -> Services
  3. Select Sql Server (MSSQLSERVER) item from services –> rightclick –> Stop Stop Sql Server (MSSQLSERVER)
  4. Open C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA
  5. Move MSDBData.mdf & MSDBlog.ldf to any other place
  6. Then Copy this Files Again from new place and put it in older place

    C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA

  7. In opened connection in object Explorer –> rightclick –> Start
  8. Then Refresh DataBase.
  9. Then you can Detach the MSDB File

The 2nd solution worked for me.

Note : I had to get “msdb” database mdf and ldf files from another working machine to get it working.


database ‘msdb’ cannot be opened. it has been marked suspect by recovery 2008 error code 926
Repair SQL Server Database marked as Suspect or Corrupted

I am using SQL server 2008, i got suddenly today an error while i was accessing database from visual studio the error is database ‘msdb’ cannot be opened. it has been marked suspect by recovery 2008 error code 926

error while accessing database

don’t know what to do to get out from this type of error. any one have any idea please let me know

There can be many reasons for a SQL Server database to go in a suspect mode when you connect to it – such as the device going offline, unavailability of database files, improper shutdown etc. Consider that you have a database named ‘test’ which is in suspect mode

You can bring it online using the following steps:

  1. Reset the suspect flag
  2. Set the database to emergency mode so that it becomes read only and not accessible to others
  3. Check the integrity among all the objects
  4. Set the database to single user mode
  5. Repair the errors
  6. Set the database to multi user mode, so that it can now be accessed by others

Here is the code to do the above tasks:


Here’s the same code for you to try out

EXEC sp_resetstatus ‘test’


DBCC CheckDB (‘test’)




The fastest way is to restore the MSDB database, but if it’s your first time doing that, here’s an easier shortcut.

  1. Restore the MSDB backup onto an existing (working) database server, but use a different database name than MSDB. The restore should go quickly (because MSDB is typically very small), and you can then verify that your objects are in there.
  2. Detach the database, and copy the mdf/ldf files over to the broken instance.
  3. Move the broken mdf/ldf files somewhere for safekeeping, and replace them with your newly restored mdf/ldf files.

Start the SQL Server instance again, and you’re set.

One gotcha – in step 1, make sure you’re restoring onto the same version of SQL Server. If the broken server is SQL Server 2005, don’t do the restore on SQL Server 2012, because the SQL 2005 instance won’t be able to attach databases that have been touched by a newer version of SQL Server.

How to recover a corrupted msdb database in SQL Server 2008?

One of our clients’ SQL Servers got corrupted. we were forced to uninstall all instances and all SQL Server programs in add/remove programs and then reinstall SQL Server because their backups were failing and useless.

I was able to re-attach the user databases but now I need to recover the SQL Server agent jobs, so first I tried creating a user database to hold the old msdb data called MSDBData_OLD, stopping the SQL Server service, replacing the .mdf file with the corrupted msdb’s .mdf file and deleteing the .ldf file, which would normally result in the database getting marked SUSPECT, and I could take it from there, but when I start the service again and click the database it says:

The database MSDBData_OLD is not accessible (ObjectExplorer)

Next I tried attaching with the log file and I got this:

SQL Error

Finally, I tried simply attaching the msdb database as a user database, but when I do, I get:

File activation failure. The physical file name “D:\SQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf” may be incorrect. The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure.

D:\SQL\MSSQL10_50_.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf is the path of the old and restored SQL Server msdb database log file.

We are running SQL Server 2008 R2 64 bit SP1.

Is there any way to recover from this or am I forced to rebuild the jobs from scratch?


Dynamic Nivo Slider Using ASP .net C# jQuery SQL Server

I have searched in google at least 2 hours to get a code to designed a dynamic slider but I have failed to fulfill my requirements. I have code like this to do this and want to share with you to save your valuable time. Just follow the steps…

Step-1: jQuery and Nivo Plug-ins:

jquery-2.0.3.min.js  and nivoSlider.js

Step-2: Database Table (MS SQL Server)

CREATE TABLE [dbo].[tblSlider](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Photo] [image] NULL,
[Name] [varchar](100) NULL,
[Description] [nvarchar](500) NULL,
[Type] [varchar](50) NULL,
[Id] ASC

Step-3: jQuery Code

<script type=”text/javascript” src=”jquery/jquery-2.0.3.min.js”></script>

<script type=”text/javascript” src=”jquery/nivoSlider.js”></script>
<script type=”text/javascript”>
$(window).load(function () {
effect: ‘random’,
animSpeed: 500,
pauseTime: 8000

Step-4: HTML and Code

<div class=”container-slider”>
<div id=”slider” class=”nivoSlider”>
<asp:Repeater ID=”Repeater” runat=”server”>
<asp:Image ID=”ImageUserId” Width=”780px” Height=”205px” runat=”server” ImageUrl='<%#”Slider.ashx?qsId=” + Eval(“Id”)  %>’ title='<%#Eval(“Description”)  %>’ />

Step-5: C# Code behind

String strqs = ” SELECT Id, Description  FROM tblSlider “;
DataTable dt = new DataTable();
dt = ClsCommon.GetAdhocResult(strqs).Tables[0];

Repeater.DataSource = dt;
catch (Exception ex) { }

Step-6: Slider.ashx  Handler Code

string conString = ConfigurationManager.ConnectionStrings[“iict”].ConnectionString;
SqlConnection myConnection = new SqlConnection(conString);
string sql = “SELECT Photo FROM tblSlider WHERE Id=@Id”;
SqlCommand cmd = new SqlCommand(sql, myConnection);

cmd.Parameters.Add(“@Id”, SqlDbType.Int).Value = context.Request.QueryString[“qsId”];
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)

catch (Exception ex) { }

That’s all… Thank you…