Search

Tuesday, June 19, 2012

SQL server could not start cannot find object or property

SQL server could not start cannot find object or property (0×80092004)
Recently I got an error in my colleague's system that he couldn’t connect the SQL server and it’s throwing error. I checked the SQL server status in configuration manager and found that the server 2008 r2 stopped.  I tried to start the SQL server but it’s not started and its shows could not start the service. I went to the application log it has so many error messages.
The Event Viewer is showing below error:
CPU time stamp frequency has changed from 215247 to 3092931 ticks per millisecond. The new frequency will be used.
I searched in the internet for the error and found that most of the posts and forum says it’s because of VIA protocol enabled. I cheked and found that the protocol is not enabled.
I tried with  changing Log On account from Network Service to Local Service and also to Local system but the Server not started. 
Finally I solved the problem by another method: 
Run > Control panel > Administrative Tools > Services
Go to Log On Tab - and changed the Log On as to Local system Account. and apply this setting and started the Service and now the service is started.

Monday, June 18, 2012

SQL Alter a column with a default value

If a column has a default value it means there is a constraint on that column setting it the default value.  The alter command will give you an error like this:


the object is dependent on column .


I found a script for altering several columns in different tables, which alter columns from float to decimal, and all of them had default value=0.


DECLARE @col nvarchar(100)
DECLARE @tabel nvarchar(100)
DECLARE @constr nvarchar(100)
declare @sql nvarchar(500)


DECLARE cTemp CURSOR LOCAL FOR select t_obj.name as TABLE_NAME
,col.name as COLUMN_NAME
,c_obj.name as CONSTRAINT_NAME
from sysobjects c_obj
join syscomments com on c_obj.id = com.id
join sysobjects t_obj on c_obj.parent_obj = t_obj.id
join    sysconstraints con on c_obj.id = con.constid
join syscolumns col on t_obj.id = col.id
and con.colid = col.colid where col.name=’col1' or col.name=’col2'  –etc


OPEN cTemp


FETCH NEXT FROM cTemp INTO @tabel, @col, @constr
WHILE @@FETCH_STATUS = 0
BEGIN


SET @sql = ‘ALTER TABLE ‘+@tabel+’ DROP CONSTRAINT ‘+ @constr
PRINT @sql
EXEC sp_executesql @sql


SET @sql = ‘ALTER TABLE ‘+@tabel+’ ALTER COLUMN ‘+@col+’ DECIMAL(14, 6)’
PRINT @sql
EXEC sp_executesql @sql


SET @sql=’alter table ‘+@tabel+’ ADD CONSTRAINT ‘+@constr+’  DEFAULT 0 FOR ‘+ @col
PRINT @sql
EXEC sp_executesql @sql


FETCH NEXT FROM cTemp INTO @tabel, @col, @constr
END
CLOSE cTemp
DEALLOCATE cTemp


This script will drop the constraints for these columns, alter the columns and then rebuild the constraints. In the select from the cursor you can include the column with the default value, if you need to modify the script for columns with different default values.


Ref: http://kb.softescu.ro/programming/p-tsql/sql-alter-a-column-with-a-default-value/

Saturday, June 16, 2012

Error: 3241, The Media Family on Device is Incorrectly Formed.

Today I was trying to restore a database backup using SSMS. The backup was sent by my friend through FTP. But SSMS raised the following error:


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


The media family on device 'C:\Temp\DB_Customer.bak' is incorrectly formed. SQL Server cannot process this media family.
RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3241) 


The main cause of the problem was backup was corrupted. The file was transferred using FTP in text mode rather than binary mode.


The backup file was transferred again using FTP in binary mode. Then the restore operation was successful.

Friday, June 15, 2012

Delete or truncate all tables data within a database SQL Server 2008 R2

Today I got one requirement from my collegue to delete all records from all Tables in the database. To do this we had to use either Delete OR Truncate command. If we use Delete command than it maintains command history in LDF and if you use Truncate it won’t so I have decided to use Truncate.


The database was having more than 150 tables and each table was having constraints like Primary Key, Foreign Key because of which we could not Truncate or Delete records from tables.


To accomplish this task first we will have to remove all the constraints which was a time consuming and tedious job so I have searched for disabling the constraints and used below command (which comes with SQL Server 2008 R2 itself)


– disable all constraints
EXEC sp_msforeachtable “ALTER TABLE ? NOCHECK CONSTRAINT all”


– TRUNCATE records from all tables
EXEC sp_MSForEachTable “TRUNCATE TABLE ?”


– enable all constraints
exec sp_msforeachtable “ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all”



Thursday, June 14, 2012

Using Databases on WP7

From version 7.5 (Mango) WP7 runs a version of SQL Server CE which is all setup waiting for your applications to make use of it. The good news is that this couldn’t be easier. One note though the phone does not include ADO.Net so the only way to query the database is via LinqToSql not that this is a problem.
Lets run through a quick example of how this works…
Create a new Windows Phone Application project in Visual Studio making sure to set the Windows Phone OS version to 7.1
projecttarget
Add a reference to System.Data.Linq.
Next we need to define our model, create a Models folder in your project and add a class called Film to it. Edit your new Film class to look like this….
using System;
using System.Data.Linq.Mapping;
namespace DatabasesExample.Models
{
    [Table]
    public class Film
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int Id { get; set; }
        [Column(CanBeNull=false)]
        public string Name { get; set; }
        [Column]
        public DateTime ReleaseDate { get; set; }
        [Column]
        public string Description { get; set; }
    }
}
You can see we are making use of the Linq Mapping attributes in order to describe how the table schema should look. We then need to create a DataContext class, to do this create a new class in Models called MyContext and make it look like this…..
using System.Data.Linq;
namespace DatabasesExample.Models
{
    public class MyContext : DataContext
    {
        public Table<film> Films;
        public MyContext() : base("DataSource=isostore:/MyDatabase.sdf;") { }
    }
}
You can change MyDatabase to be whatever name you want your database to be stored under in Isolated Storage. The last thing that needs to be done before we can start accessing our database is to tell the application to physically create the database. This can be done by adding the following code to your main App.cs constructor…
using (var myContext = new MyContext())
{
    if (!myContext.DatabaseExists())
        myContext.CreateDatabase();
}
On start your application will then check if the database exists, if it doesn’t it will create it.
We can now access it using LinqToSql, lets say we wanted to add a new film to the films table…
var myContext = new MyContext();
var ConAir = new Film { Name="Con Air", Description="Planes And Guns", ReleaseDate = new DateTime(1997,6,2) };
myContext.Films.InsertOnSubmit(ConAir);
myContext.SubmitChanges();
Or if we wanted to get a list of all the films…
var myContext = new MyContext();
var films = (from film in myContext.Films select film).ToList() ;

Schema Modifications

Unfortunately updating a tables schema or adding new tables isn’t as simple as just changing the model or the context. The best way to achieve this is to version your database and use the DatabaseSchemaUpdater object. For this example lets assume the database in its current state is version 0 (The default version) and we are working on changes to make it version 1. Lets assume we have created a new MusicAlbum class much like our Film class and updated our MyContext to have a second table called MusicAlbums. In your main app.cs class add the following
private int dbVersion = 1;
Now we need to modify our DB creation code to look like this….
using (var myContext = new MyContext())
{
    if (myContext.DatabaseExists() == false)
    {
        myContext.CreateDatabase();
        DatabaseSchemaUpdater dbUpdater = myContext.CreateDatabaseSchemaUpdater();
        dbUpdater.DatabaseSchemaVersion = dbVersion;
        dbUpdater.Execute();
    }
    else
    {
        DatabaseSchemaUpdater dbUpdater = myContext.CreateDatabaseSchemaUpdater();
        if (dbUpdater.DatabaseSchemaVersion < dbVersion)
        {
            if (dbUpdater.DatabaseSchemaVersion < 1)
                dbUpdater.AddTable<musicalbum>();
            dbUpdater.DatabaseSchemaVersion = dbVersion;
            dbUpdater.Execute();
        }
    }
}
The default version for a database schema is zero and as we never specified a version when we first created the database that is what version our database currently is. So if you run the application with the above changes (Assuming you have created a MusicAlbum class and updated the MyContext class to have the new table) then the new MusicAlbum table will get created as soon as it launches. The DatabaseSchemaUpdater class also has methods for AddIndex and AddColumn. When adding columns you need to either make the column nullable or set a default value so existing records can be populated. This can be done by using attributes on the property like this…
[Column(DbType = "int DEFAULT 0 NOT NULL ")]
public int Rating{get;set;}
One thing to note is that in the current version there is no way for the DatabaseSchemaUpdater to remove columns so be a bit careful with what you create.
Ref: