Home » SQL Server

Restoring Database from .bak error: object cannot be cast from dbnull

I am attempting to restore a database on a Windows SQL 2008 Server from a .bak file. The .bak file was created on another machine running Windows SQL 2005 Server. It was copied between the two machines using an external HDD.

The error message is "Object cannot be cast from DbNull to other types". It appears when I click the 'contents' button in the Specify Backup dialog box after pressing 'add' [media] to specify the name and location of the .bak file. The .bak was copied from the external HDD onto an internal HDD (d:\backups\testme.bak)

I presume that the error message means that the contents of the file cannot be recognised. Does this mean that the .bak file is corrupt. What else might cause this problem?

I can restore the database from a .DMP (dump) file, but would prefer to use .BAK so in future I can just restore the changed records.


1. Log-in as the System Administrator (sa).

2. Select Databases and right click | Restore from Backup

3. Restore dialog set To = Image (name of new database) and From = Device, then click '...' button

4.  Specify Backup dialog box - click 'Add'

5. Add Media dialog - Browse and select Image.bak (not in the default SQL directory for backups). Press OK to return to the Specify Backup dialog box.

6. Specify Backup dialog box - click 'Contents' button and get error message "Object cannot be cast from DbNull to other types"


5 Answers Found


Answer 1

You will probably need to go all scripty to fix this.

The first command is:

RESTORE HEADERONLY from disk = '<full path and filename of backup file>'

Post back any errors or results.


Answer 2


I suspect that your backup file has been corrupted. Please also run RESTORE VERIFYONLY (http://msdn.microsoft.com/en-us/library/ms188902.aspx) statement to check this backup set. If it actually corrupted, please try to use another copy backup file of the source database.



Answer 3

Looks like corruption.Another reason using WITH CHECKSUM, CONTINUE_AFTER_ERROR; within BACKUP DATABASE command



Answer 4

executing a RESTORE VERIFYONLY query yielded the error message "not a valid Microsoft Tape Format backup". Therefore, it seems that my backup file is indeed corrupt.

Makes the point that there is no point in doing backups without also doing an occasional restore!


Answer 5

Yep, only the actual restore database command will 'say' whether the .BAK is corrupted or not..





i am using a web service
wrtitten in .net and i access the webservice from my wepApplication i get this error
 System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> Object cannot be cast from DBNull to other types.

my code is access webservice:
protected void btnSave_Click(object sender, EventArgs e)
            int intStatusCode;
            dtProjectStatus = (DataTable)ViewState["dtProjectStatus"];
                objService.Credentials = System.Net.CredentialCache.DefaultCredentials;
                  intStatusCode = objService.InsertTest(dtProjectStatus);
            catch (Exception ex)
                throw ex;

        and i checked the Table dtProjectStatus has rows.

   My webservice code:

    public int InsertTest(DataTable dt)
        return objProject.OrderStatusCode;


   MY business logic code:
     public int InsertTest(DataTable dt)

                SqlParameter[] pOrder =
                    new SqlParameter("@ID", SqlDbType.VarChar, 10,"ID"),
                    new SqlParameter("@Dept", SqlDbType.VarChar,50, "Dept"),                    
                    new SqlParameter("@StatusCode",SqlDbType.Int,4,ParameterDirection.Output,false,0,0,"",DataRowVersion.Original,OrderStatusCode)

                SqlHelper.DataTableInsert("mrm_InsertMobileClient_Test", pOrder, dt);
                OrderStatusCode = Convert.ToInt32(pOrder[2].Value);

                return OrderStatusCode;
            catch (Exception ex)
                throw ex;


MY stored procedure:

 create Procedure [dbo].[mrm_InsertMobileClient_Test]
 @ID varchar(50),  
 @Dept varchar(50),
 @StatusCode int output      
   INSERT INTO dbo.kk
  SET @StatusCode =SCOPE_IDENTITY()     
  RETURN @StatusCode

   But checked the database the table values are stored fine, but this exception was thrown [System.Web.Services.Protocols.SoapException: Server was unable

to process request. ---> Object cannot be cast from DBNull to other types]

 How to overcome this exception?

thanks and regards



Case "System.Int32"
                Return Convert.ToInt32(a) + Convert.ToInt32(b)

Object cannot be cast from DBNull to other types


Im receving a runtime error for this, and I've checked other posts for similar errors, but this error is different.  Does anybody have a clue?

Under Locals/ arparams/ for the first parameter "0" the more detail error reports:

"Data is Null, the method or property cannot cannot be called on null values"

Im rewriting this program in the 4.0 framework from 2.0, utilizing VisualStudio2010.

This ran fine previously without any erros in .NET 2.0. 

Here is the C# which collects the parameters and calls the stored proceedure. 

Here the first parameter strProjectID will be "" because this is a new project:

public static int SaveProject(string strProjectID, string strProjectName, string strProjectDesc, string strProjectNotes, string strProjectDate, string strProjectType)
            // Update Project within hip_Project
            int newprojectid;
            SqlParameter[] arParms = new SqlParameter[6];

            arParms[0] = new SqlParameter("@pProjId", SqlDbType.Int, 1);
            if (strProjectID == "")
                arParms[0].Value = DBNull.Value;
                arParms[0].Value = strProjectID;
            arParms[0].Direction = ParameterDirection.Input;

            arParms[1] = new SqlParameter("@pProjName", SqlDbType.VarChar, 255);
            arParms[1].Value = strProjectName;
            arParms[1].Direction = ParameterDirection.Input;

            arParms[2] = new SqlParameter("@pProjDesc", SqlDbType.VarChar, 1000);
            arParms[2].Value = strProjectDesc;
            arParms[2].Direction = ParameterDirection.Input;

            arParms[3] = new SqlParameter("@pProjNotes", SqlDbType.VarChar, 8000);
            arParms[3].Value = strProjectNotes;
            arParms[3].Direction = ParameterDirection.Input;

            arParms[4] = new SqlParameter("@pProjDate", SqlDbType.DateTime, 8);
            arParms[4].Value = strProjectDate;
            arParms[4].Direction = ParameterDirection.Input;

            arParms[5] = new SqlParameter("@pProjType", SqlDbType.Int, 1);
            if (strProjectType == "True")
                arParms[5].Value = 1;
                arParms[5].Value = 0;
            arParms[5].Direction = ParameterDirection.Input;

                //SqlHelper.ExecuteNonQuery(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString, CommandType.StoredProcedure, "hip_InsUpdProj", arParms);
                newprojectid = Convert.ToInt32(SqlHelper.ExecuteScalar(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString, CommandType.StoredProcedure, "hip_InsUpdProj", arParms));
                return newprojectid;
            catch (Exception exCallInsertOrgSP)
                throw exCallInsertOrgSP;

Here is the original stored proceedure using SQL Server 2000.  Now Im using SQL Server 2008:

CREATE proc dbo.hip_InsUpdProj
@pProjId	                int,
@pProjName               varchar(255),
@pProjDesc                varchar(1000),
@pProjNotes	varchar(8000),
@pProjDate	datetime,
@pProjType	int

	@RC	int,
	@ROWS	int

if @pProjId = null
	insert into hip_Project (ProjectName, ProjectDesc, ProjectNotes, dtCreated)
	values (@pProjName, @pProjDesc, @pProjNotes, @pProjDate)
	update hip_Project
	set ProjectName = @pProjName,
		ProjectDesc = @pProjDesc,
		ProjectNotes = @pProjNotes,
		dtCreated = @pProjDate,
		deleted = @pProjType
	where Project_Id = @pProjId

if @pProjId = null
	SELECT @pProjId as newProjectID
return 0


I did find a workaround just passing in 0 instead of using DBNulls, but I would still like to find out why this problem exists?

Please let me know if you need further analysis, thank you in advance for your help!



I have a .bak database file and i want to restore it to a new database so that i can get the data inside the .bak file

I am using SSMS 2008 Express

what i did :

I created a database with the same name as of my .bak file (in my case "RM")

now after creating a new database > righclick  on database > tasks > restore

Selected FROM : RM ( empty database that i just created)

Selected TO : RM.bak (my backup file)

when i press "Ok"

i get this error:


I have been struggling to import my .bak files into my sql server database.  I have contacted the hosting copany who say it is just not possible.   

This is all new to me, but I find it hard to believe, otherwise, why would I have been supplied .bak files in the first place?

Any help would be much appreciated.


Please help -

I have WCF generated classes that I have exposed with a COM interface using partial classes. When I call the web service methods through a .net client everything works fine, but when I call them from a C++ client through COM I get a serialization error deep in the serializer when it tries to serialize any array property.

The exposed classes have the following attributes: ComVisible(true), GuidAttribute("..."), ProgId("..."), and ClassInterface(ClassInterfaceType.None)

The exposed interfaces have the following attributes: ComVisible(true), GuidAttribute("..."), and InterfaceType(ComInterfaceType.InterfaceIsDual)

The error message I get is: Unable to cast object of type Company.Designer.ServiceProxy.IField[] to type Company.Designer.ServiceProxy.Field[]

All objects are using DataContract serialization.

Any help will be appreciated.





I am restoring a production database to test. It was taking a very long time to start and I thought it was hung up. I hit stop on the Restore. I rebooted the server. Now on my db it say LogosTestDB (Restoring.....). How can stop this process so I can restart the restore? Thanks for your Help
I've got a database from a client (SQL 2008) and when I try and restore the database to my server, I get the following error: specified cast is not valid...

I get the error as I browse for and select the backup file.

Please help!!!

Hello to all,

I've spent the last three day on this. Hope someone can shed some light on the problem.

I have a datagridview I which to total a column and place in a textbox.  with the coding below I do get the first number and it is place correctly in the textbox but when I complete the data row and move to the next, I receive the following error. "object cannot be cast from DBNull to other  type."    Read and tried a lot of ideas on line , could not get any of them to work. 

PrivateFunction TotalPrice() AsDouble

        Dim price AsDouble = 0

        Dim p As Integer = 0

        For p = 0 To WinePurchaseDataGridView.Rows.Count - 1

            price += Convert.ToDouble(WinePurchaseDataGridView.Rows(p).Cells("DataGridViewTextBoxColumn5").Value)

        Next p

        Return price


PrivateSub WinePurchaseDataGridViewDataGridView_CurrentCellChanged(ByVal sender AsObject, ByVal e As System.EventArgs) Handles WinePurchaseDataGridView.CurrentCellChanged

        If WinePurchaseDataGridView.Rows.Count > 0 Then

            CurrentValueTextBox.Text = TotalPrice().ToString("c")




Before uninstalling TFS 2010 RC I've created back up for each data base. After I installed Normal TFS 2010 release I can't attach those collections. Is it possible to restore them now? Or source codes will be lost ?


Hello Friends

i want to know that whether there is any provision in SQL Server 2008 to restore MDF file only from the bak file excluding the log file.

i just want to know because, the bak file which i have is close to 4-5 GB, but after specifying the details while restoring the database, then it is consuming close to 80 GB as 30GB for the MDF file or 50 GB for log file.

But say for once, the total hard disk is 80 GB.

all the given figures are approximate except for Hard Disk size.

in that case, i only want to extract the MDF file while excluding the LOG file for the database to attach.

Looking for favorable replies.

How can I restore a BAK file that I received from a vendor.  They were unable to find a database schema for us so they just sent us a BAK file.  I'm using SQL Server Express 2008

I can restore all the data base to new SQL except SharePoint_config.

Currently I am getting this error on restoring SharePoint_Config:

Msg 3159, Level 16, State 1, Line 2

The tail of the log for the database "SharePoint_Config" has not been backed up. Use BACKUP LOG WITH NORECOVERY to backup the log if it contains work you do not want to lose. Use the WITH REPLACE or WITH STOPAT clause of the RESTORE statement to just overwrite the contents of the log.

Msg 3013, Level 16, State 1, Line 2

RESTORE DATABASE is terminating abnormally.



I cannot delete the data base from that SharePoint_config and I get:

TITLE: Microsoft SQL Server Management Studio



Drop failed for Database 'SharePoint_Config'.  (Microsoft.SqlServer.Smo)


For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600.1+((KJ_RTM).100402-1540+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Drop+Database&LinkId=20476





An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)




Cannot drop database "SharePoint_Config" because it is currently in use. (Microsoft SQL Server, Error: 3702)


For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600&EvtSrc=MSSQLServer&EvtID=3702&LinkId=20476







I building a simple utility to restore bak file into DB


1.       I  Referenced Microsoft.SqlServer.Smo.dll v10 and trying to create a Server object.

Compile error was: 'Microsoft.SqlServer.Management.Sdk.Sfc.ISfcPropertyProvider' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.SqlServer.Management.Sdk.Sfc, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91'


2.       Although MSDN indicates not to reference this dll I added a reference to this assembly and now Server is created


3.       Now I am trying to create Restore object – but this type could not be found in the Microsoft.SqlServer.Management.Smo namespace


4.       Referencing version of Microsoft.SqlServer.Smo.dll (which was not in the VS2008 assembly list and could be referenced only by manually edit the project file) solved all compilation errors


5.       I am using a VS 2008 SP1 on a machine but the target framework of the project  is .NET Framework 2.0. No SQL server installed on the development machine.



6.       After compiling I deployed it (simply copied the exe) to a machine with SQLexpress DB and .NET 2.0. Running the program caused an error: Could not load file or assembly 'Microsoft.SqlServer.SqlClrProvider, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.


7.       What am I missing?







I have a backup file say x.bak.dap

I want to restore this file which has the .dap extension

How to do it?

Please suggest me

Thanks in advance,

Senthil N


anyone can help me...

here's my error...

Exception Details: System.InvalidCastException: Object cannot be cast from DBNull to other types.

here's my code.

double totald = Convert.ToDouble(drReaderdeduc["TAMT"]);
totaldeduc.Text = String.Format("{0:N2}", totald);

the problem is the query output is null but i convert.todouble so got an error... what is the best solution if the record is null??? please help....


We have to do a lot of restore from backups for a development on a production sql 2008 server.

This daily job or by request job will have 3 steps.

Step 1 kill the user that was using such @dbname

declare killprocess_cursor cursor for
select a.spid from sysprocesses a join
sysdatabases b on a.dbid=b.dbid where b.name=@dbname


Step 2 Restore database, from a fixed path using a T-Sql

RESTORE DATABASE db_abc FROM DISK = 'H:\RestoreDB\db_abc_FullBK.bak' with replace

Step 3 restore users


Sometimes the daily job will fail at 2. The by request job will fail at 1.

I am concern with daily job failure now. Error message:

Executed as user: myDomain\myISAgentAcct. Exclusive access could not be obtained because the database is in use. [SQLSTATE 42000] (Error 3101)  RESTORE DATABASE is terminating abnormally. [SQLSTATE 42000] (Error 3013).  The step failed.


When I use sp_who2, there is none using the db and rerun result with the same error. I have to take it offline, detach, attach again and rerun the job to finish it without error.


What bugs me... the job will run for in most days and fail in other. I already has a kill user step and no one works at the schedule night time.

My last suspicion... either Report service has a hold on it (that not show in sp_who2 or the cursor), or the constant running 'checkpoint' on msdb or master will prevent a restore.



When I open up my existing SSIS project, I always get this error.  Does anyone know what was wrong ?

TITLE: Microsoft Visual Studio

Unable to cast COM object of type 'Microsoft.SqlServer.Dts.Runtime.Wrapper.PackageNeutralClass' to interface type 'Microsoft.SqlServer.Dts.Runtime.IObjectWithSite'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{FC4801A3-2BA9-11CF-A229-00AA003D7352}' failed due to the following error: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).


I'm having an issue calling a COM object function from .NET C# client program. The COM object is written in C++ unmanaged. The problem only appears when I'm calling from a worker thread, it works fine if I call it from the UI thread. This is the error:

Unable to cast COM object of type 'gvAgileFileReaderLib.gvAgileFileReaderClass' to interface type 'gvAgileFileReaderLib.IgvMpiRead'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{616B5C39-C7FB-4C8C-85D4-27559DD83304}' failed due to the following error: Unspecified error (Exception from HRESULT: 0x80004005 (E_FAIL)).

I have tried the following methods but all of them fails:

1) Create the COM object on UI thread, and call its function via its interface (IgvMpiRead) in the worker thread

2) Create the COM object on the worker thread & access its function from worker thread

3) Tried with worker thread set to STA & MTA

I need to use the COM function is a worker thread to prevent a long processing from holding up my UI, but it just doesn't work when I try to call the COM function inside the worker thread.

The weird thing is that doing the same from a unmanaged C++ client works fine (I can create the com object on UI, and then call its function from worker thread). Is this problem caused by interop issues? I'm using the interop that Visual Studio 2010 creates for me when I add reference to the C++ COM object.







I'm trying to use the Restore.Abort function during an SMO restore process - What would be the best method?
(Posted on the SQL SMO forum but suggested I post here too)



Sub DoRestore(ByVal DatabaseName As String, ByVal BackupFilePath As String, ByVal SQLServerName As String)
  Dim svr As Server = New Server(SQLServerName)
  Dim res As Restore = New Restore()


   res.Devices.AddDevice(BackupFilePath, DeviceType.File)
   res.Database = DatabaseName
   res.ReplaceDatabase = True
   res.PercentCompleteNotification = 10

   AddHandler res.PercentComplete, AddressOf ProgressEventHandler
   AddHandler res.Complete, AddressOf CompleteEventHandler
   While m_Cancel = True
   End While
  Catch ex As Exception
  End Try
 End Sub
	 Private Function ProgressEventHandler(ByVal sender As Object, ByVal e As PercentCompleteEventArgs)
	 If m_Cancel Then
   'Return CopyProgressResult.Cancel
  End If
   SetControlPropertyValue(ProgressBar, "value", e.Percent)
   SetControlPropertyValue(Label3, "text", e.Percent.ToString & " % Complete")
 End Function
 Private Sub CompleteEventHandler(ByVal sender As Object, ByVal e As Microsoft.SqlServer.Management.Common.ServerMessageEventArgs)
   MessageBox.Show("Restore Complete")
  ButtonCancel.enabled = false
 End Sub


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure