Friday, September 26, 2014

Restoring Orphaned MDF File in SQL Server


You can attach the database using CREATE DATABASE FOR ATTACH_REBUILD_LOG.

http://msdn.microsoft.com/en-us/library/ms176061.aspx

If that doesn't work, you can try the undocumented FOR ATTACH_FORCE_REBUILD_LOG.


CREATE DATABASE < YOURDBNAME > ON (FILENAME = 'D:\<YOURMDFNAME>.mdf')
FOR ATTACH_FORCE_REBUILD_LOG



From Management Studio


Attaching the .mdf file through the management console, without a .ldf file

1. right click "Databases" and select attach.
2. Click on "add" and select the .mdf file, click OK.
3. In the details panel select the .dlf file, click remove button.
4. Click the main OK button.

Thursday, September 25, 2014

Total number of error messages in SQL Server = 10548

SELECT message_id
 ,severity
 ,TEXT
FROM sys.messages
WHERE language_id = 1033;

The MSSQLServer service terminated unexpectedly. Check the SQL Server error log and Windows System and Application event logs for possible causes.




Solution: 


Oops! You might be running a very old build of SQL Server. Immediately check for new release of Service Packs, I would recommend installing recent service pack and then the latest cumulative update package.


If the Service pack installation didn't solve your Issue

For additional help, Open a case with Microsoft immediately.

Wednesday, September 24, 2014

Script to generate drop all tables statements in a database in SQL Server

SELECT 'Drop table ' + NAME
FROM sys.objects
WHERE schema_name(schema_id) = 'dbo'
 AND type = 'u'

Script to delete millions of records without increasing your log size in SQL Server

DECLARE @continue INT
DECLARE @rowcount INT

SET @continue = 1

WHILE @continue = 1
BEGIN
 PRINT GETDATE()

 SET ROWCOUNT 10000     --Replace 10000 as required


 BEGIN TRANSACTION

 DELETE
 FROM dbo.Transactions
 WHERE TranDate IS NULL --Replace your delete script here

 SET @rowcount = @@rowcount

 COMMIT

 PRINT GETDATE()

 IF @rowcount = 0
 BEGIN
  SET @continue = 0
 END
END

Tuesday, September 23, 2014

Script to find port number of a SQL Server instance in Multiple ways

--Method 1
DECLARE @tcp_port NVARCHAR(5)

EXEC xp_regread @rootkey = 'HKEY_LOCAL_MACHINE'
 ,@key = 'SOFTWARE\MICROSOFT\MSSQLSERVER\MSSQLSERVER\SUPERSOCKETNETLIB\TCP'
 ,@value_name = 'TcpPort'
 ,@value = @tcp_port OUTPUT

SELECT @tcp_port


--Method 2
sp_readerrorlog 1
 ,1
 ,'listening'
 ,'server'





--Method 3
SELECT SERVERNAME = CONVERT(NVARCHAR(128), SERVERPROPERTY('SERVERNAME'))
 ,LOCAL_NET_ADDRESS AS 'IPAddressOfSQLServer'
 ,local_tcp_port AS 'PortNumber'
FROM SYS.DM_EXEC_CONNECTIONS
WHERE SESSION_ID = @@SPID

Script to sync up logins and database users in SQL Server

USE DATABASE
GO

EXEC sp_change_users_login 'update_one'
 ,'databse username'
 ,'loginname'
GO