7developers blog

Useful articles, videos and code examples from professional developers

Database recovery on SQL server 2005-2008

You could get data loss but it could be done.
1. Detach database and move your mdf to save location.
2. Create new database of same name, same files, same file location and same file size.
3. Stop SQL server.
4. Swap mdf file of just created DB to your save one.
5. Start SQL. DB will go suspect.
6. ALTER DATABASE yourdb SET EMERGENCY7. ALTER DATABASE yourdb SET SINGLE_USER8. DBCC CHECKDB (yourdb, REPAIR_ALLOW_DATA_LOSS)
9. ALTER DATABASE yourdb SET MULTI_USER10. ALTER DATABASE yourdb SET ONLINE


source

Microsoft Sql Managment studio 2008 repair

So I first did this:


C:\windows\system32 > regsvr32.exe /u actxprxy.dll

and then register it again:


C:\windows\system32 > regsvr32.exe actxprxy.dll

regsvr32 "C:\Program Files\Internet Explorer\ieproxy.dll"

if you are running 64 bit windows, try this:

regsvr32 "C:\Program Files (x86)\Internet Explorer\ieproxy.dll"

C # Get access to private class members using Reflection


Type type = Request.GetType();
PropertyInfo property = type.GetProperty("QueryStringBytes",
BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.NonPublic);
byte[] queryBytes = (byte[])property.GetValue(Request, null);
string querystring = HttpUtility.UrlDecode(queryBytes, Encoding.UTF8);


C# DateTime Extensions

How do I extend a class with c# extension methods?
public static class DateTimeExtensions
{
    /// 
    /// Return the date that is the start of the week relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetStartOfWeek(this DateTime date)
    {
        DayOfWeek day = date.DayOfWeek;
        int days = day - DayOfWeek.Monday;
        DateTime start = DateTime.Now.AddDays(-days);
        return start.Date;
    }

    /// 
    /// Return the date that is the start of the week relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetStartOfLastWeek(this DateTime date)
    {
        return date.GetStartOfWeek().AddDays(-7);
    }

    /// 
    /// Return the date that is the end of the week relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetEndOfWeek(this DateTime date)
    {
        return date.GetStartOfWeek().AddDays(6);
    }

    /// 
    /// Return the date that is the end of the week relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetEndOfLastWeek(this DateTime date)
    {
        return date.GetEndOfWeek().AddDays(-7);
    }

    /// 
    /// Return the date that is the start of the month relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetStartOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, 1);
    }

    /// 
    /// Return the date that is the start of previous month relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetStartOfLastMonth(this DateTime date)
    {
        return date.GetStartOfMonth().AddMonths(-1);
    }

    /// 
    /// Return the date that is the end of the month relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetEndOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, date.GetDaysInMonth(), 23, 59, 59, 999);
    }

    /// 
    /// Return the date that is the start of previous month relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetEndOfLastMonth(this DateTime date)
    {
        return date.GetStartOfLastMonth().GetEndOfMonth();
    }

    /// 
    /// Returns the number of days in the month of the specified date.
    /// 
    /// 
    /// 
    public static int GetDaysInMonth(this DateTime date)
    {
        return DateTime.DaysInMonth(date.Year, date.Month);
    }

    /// 
    /// Return the first day of the year relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetStartOfYear(this DateTime date)
    {
        return new DateTime(date.Year, 1, 1);
    }

    /// 
    /// Return the first day of the last year relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetStartOfLastYear(this DateTime date)
    {
        return new DateTime(date.Year - 1, 1, 1);
    }

    /// 
    /// Return the last day of the year relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetEndOfYear(this DateTime date)
    {
        return new DateTime(date.Year, 12, 31, 23, 59, 59, 999);
    }

    /// 
    /// Return the last day of the last year relative to the specified date.
    /// 
    /// 
    /// 
    public static DateTime GetEndOfLastYear(this DateTime date)
    {
        return new DateTime(date.Year - 1, 12, 31, 23, 59, 59, 999);
    }

}

Get some hardware information via sql query on MS sql server

SELECT        cpu_count AS '# of Cores', hyperthread_ratio AS '# of Threads',
 cpu_count / hyperthread_ratio AS 'Physical CPU Count', 
                         physical_memory_in_bytes / 1048576 AS 'Physical memory (MB)'
FROM            sys.dm_os_sys_info
Result:

# of Cores   # of Threads   Physical CPU Count      Physical memory (MB)


4                      4                             1                                   8103




Cross table (pivot) using sql query on Microsoft SQL Server

So, we have 3 columns usually DateTime, Value and Name
Simple sql query:
select [DateTimeSaved], NValue,m.DPT_Name from NumericValues n 
inner join DataPoints m on n.DataPointId=m.DataPointId
Result:

DateTimeSaved

Nvalue

DPT_NAME

9/26/11

11.8

USDbuy

2/7/12

15.7

EURbuy

2/5/12

15.7

EURbuy

2/3/12

15.7

EURbuy

2/2/12

15.62

EURbuy

2/1/12

15.45

EURbuy

1/31/12

15.45

EURbuy

1/30/12

15.4

EURbuy

1/29/12

15.3

EURbuy

1/28/12

15.3

EURbuy

We need transform it to cross table (pivot) like this:


(no column name)

Eurbuy

Eursell

9/26/11

15.91

16.11

9/27/11

16.09

16.35

9/29/11

16.1194

16.3581



Query:
/*if you have a lot of data, you should use temporary sql table instead of table variable */
declare @TableColumns table( DPT_NAME varchar(255) )  
/*Get and insert future column names into table variable*/
insert into @TableColumns
select distinct DPT_NAME from  DataPoints

declare @Columns varchar(Max)
Set @Columns =''

/* Create one string with column names separate by comma  */
select @Columns=@Columns+',['+ DPT_NAME+']' from  @TableColumns
Set @Columns =substring(@Columns,2,LEN(@Columns))

/*Debug message PRINT @Columns */

declare @SQL varchar(MAX)
/*Create sql query for dynamic execution*/
SET @SQL=N'Select convert(varchar, [DateTimeSaved], 101),'+@Columns+' '+

' from (' +

' select [DateTimeSaved], NValue,m.DPT_Name from NumericValues n 
inner join DataPoints m on n.DataPointId=m.DataPointId '+

') as sourcetable '+

'PIVOT ( '+

' MAX([NValue]) for DPT_Name in ('+@Columns+' ) '+

') as PivotTable '

EXEC (@SQL)

/*Where Nvalue can be string or numeric, Also you can use other aggregate functions SUM, etc */

Shrink Log file in MS SQL server 2008

USE YOUR_DB;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE YOUR_DB
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (2, 1);  -- here 2 is the file ID for trasaction log file,you can also mention the log file name (YOUR_DB_log)
GO
-- Reset the database recovery model.
ALTER DATABASE YOUR_DB
SET RECOVERY FULL;
GO


Tables' list with their size. SQL script for Microsoft SQL server

declare @RowCount int, @tablename varchar(100)
declare @Tables table (
PK int IDENTITY(1,1),
tablename varchar(100),
processed bit
)
INSERT into @Tables (tablename)
SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE' and TABLE_NAME not like 'dt%' order by TABLE_NAME asc

declare @Space table (
name varchar(100), rows nvarchar(100), reserved varchar(100), data varchar(100), index_size varchar(100), unused varchar(100)
)
select top 1 @tablename = tablename from @Tables where processed is null
SET @RowCount = 1
WHILE (@RowCount <> 0)
BEGIN
insert into @Space exec sp_spaceused @tablename
update @Tables set processed = 1 where tablename = @tablename
select top 1 @tablename = tablename from @Tables where processed is null
SET @RowCount = @@RowCount
END

update @Space set data = replace(data, ' KB', '')
update @Space set data = convert(int, data)/1000
update @Space set data = data + ' MB'
update @Space set reserved = replace(reserved, ' KB', '')
update @Space set reserved = convert(int, reserved)/1000
update @Space set reserved = reserved + ' MB'

select * from @Space order by convert(int, replace(data, ' MB', '')) desc