Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Thursday, August 16, 2018

Some useful SQL Queries


Block queries


SELECT
    spid
    ,sp.status
    ,loginame   = SUBSTRING(loginame, 1, 12)
    ,hostname   = SUBSTRING(hostname, 1, 12)
    ,blk        = CONVERT(char(3), blocked)
    ,open_tran
    ,dbname     = SUBSTRING(DB_NAME(sp.dbid),1,10)
    ,cmd
    ,waittype
    ,waittime
    ,last_batch
    ,SQLStatement       =
        SUBSTRING
        (
            qt.text,
            er.statement_start_offset/2,
            (CASE WHEN er.statement_end_offset = -1
                THEN LEN(CONVERT(nvarchar(MAX), qt.text)) * 2
                ELSE er.statement_end_offset
                END - er.statement_start_offset)/2
        )
FROM master.dbo.sysprocesses sp
LEFT JOIN sys.dm_exec_requests er
    ON er.session_id = sp.spid
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) as qt
WHERE spid IN (SELECT blocked FROM master.dbo.sysprocesses)
AND blocked = 0


      

Kill process  - kill and processID

kill 201;


check Index

select the db and run

SELECT ps.database_id, object_name(ps.OBJECT_ID) as table_name, ps.index_id, b.name as index_name, ps.avg_fragmentation_in_percent,ps.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS ps
INNER JOIN sys.indexes AS b ON ps.OBJECT_ID = b.OBJECT_ID
inner join sys.tables as c ON b.object_id = c.object_id
AND ps.index_id = b.index_id
WHERE ps.database_id = DB_ID()
and b.name is not null
ORDER BY ps.avg_fragmentation_in_percent desc



Check last executed stats


/* 1.Query to check when statistics was last executed */
SELECT
  st.object_id                          AS [Table ID]
, OBJECT_NAME(st.object_id)             AS [Table Name]
, st.name                               AS [Index Name]
, STATS_DATE(st.object_id, st.stats_id) AS [LastUpdated]
, modification_counter                  AS [Rows Modified]
FROM
sys.stats st
CROSS APPLY
sys.dm_db_stats_properties(st.object_id, st.stats_id) AS sp
WHERE
STATS_DATE(st.object_id, st.stats_id)<=DATEADD(DAY,-1,GETDATE()) 
AND modification_counter > 0
AND OBJECTPROPERTY(st.object_id,'IsUserTable')=1
order by OBJECT_NAME(st.object_id)





read sp


sp_helptext 'myDb.spName'



few




SELECT
       r.session_id
       ,st.TEXT AS batch_text
       ,SUBSTRING(st.TEXT, statement_start_offset / 2 + 1, (
                     (
                           CASE
                                  WHEN r.statement_end_offset = - 1
                                         THEN (LEN(CONVERT(NVARCHAR(max), st.TEXT)) * 2)
                                  ELSE r.statement_end_offset
                                  END
                           ) - r.statement_start_offset
                     ) / 2 + 1) AS statement_text
       ,qp.query_plan AS 'XML Plan'
       ,r.*
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS st
CROSS APPLY sys.dm_exec_query_plan(r.plan_handle) AS qp
ORDER BY cpu_time DESC





select
    P.spid,
       P.status
,   right(convert(varchar,
            dateadd(ms, datediff(ms, P.last_batch, getdate()), '1900-01-01'),
            121), 12) as 'batch_duration'
,   P.program_name
,   P.hostname
,   P.loginame
from master.dbo.sysprocesses P
where P.spid > 50
and      P.status not in ('background', 'sleeping','runnable')
and      P.cmd not in ('AWAITING COMMAND'
                    ,'MIRROR HANDLER'
                    ,'LAZY WRITER'
                    ,'CHECKPOINT SLEEP'
                    ,'RA MANAGER')
order by batch_duration desc





Some useful SQL Queries

Some Useful SQL commands
-------------------------

-- get database names
SELECT name,* FROM master.dbo.sysdatabases



Job History
-----------


USE msdb ; 
GO 

SELECT j.name JobName,h.step_name StepName,
CONVERT(CHAR(10), CAST(STR(h.run_date,8, 0) AS dateTIME), 111) RunDate,
STUFF(STUFF(RIGHT('000000' + CAST ( h.run_time AS VARCHAR(6 ) ) ,6),5,0,':'),3,0,':') RunTime,
h.run_duration StepDuration,
case h.run_status when 0 then 'failed'
when 1 then 'Succeded'
when 2 then 'Retry'
when 3 then 'Cancelled'
when 4 then 'In Progress'
end as ExecutionStatus,
h.message MessageGenerated
FROM sysjobhistory h inner join sysjobs j
ON j.job_id = h.job_id
-- name of the job
where j.name='Populate_TTC_Task_Details'
-- only failed jobs
AND h.run_status=0
ORDER BY h.run_date desc

Full Job history
------------------

USE msdb ; 
GO 

EXEC dbo.sp_help_jobhistory 
    @job_name = N'Populate_TTC_Task_Details' ; 
GO

Job names
----------
select s.name,l.name
 from  msdb..sysjobs s
 left join master.sys.syslogins l on s.owner_sid = l.sid
 order by s.name

 -- find guid from backups
use [msdb]
SELECT * FROM log_shipping_primary_databases

"D:\Program Files\Microsoft SQL Server\110\Tools\Binn\sqllogship.exe" -Backup E842CE8C-9F88-4483-B3AE-96BA97F62E25 -server ServerName



Most CPU Intensive Queries
--------------------------

--- https://www.red-gate.com/simple-talk/blogs/how-to-find-cpu-intensive-queries/

SELECT
       -- using statement_start_offset and
       -- statement_end_offset we get the query text
       -- from inside the entire batch
       SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
                           ((CASE qs.statement_end_offset
                                        WHEN -1 THEN DATALENGTH(qt.TEXT)
                                        ELSE qs.statement_end_offset
                           END
                           - qs.statement_start_offset)/2)+1)
                           as [Text],
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
-- converting microseconds to seconds
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
       -- Retrieve the query text
       CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
       -- Retrieve the query plan
       CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_worker_time DESC -- CPU time


Longest Running queries
-----------------------
SELECT  st.text,
        qp.query_plan,
total_worker_time,
        qs.*
FROM    (
    SELECT  TOP 50 *
    FROM    sys.dm_exec_query_stats
    ORDER BY total_worker_time DESC
) AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.max_worker_time > 300
      OR qs.max_elapsed_time > 300
 
 
Permission
----------
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'



Server Info
-----------

SELECT
            SERVERPROPERTY('MachineName') AS [ServerName],
SERVERPROPERTY('ServerName') AS [ServerInstanceName],
            SERVERPROPERTY('InstanceName') AS [Instance],
            SERVERPROPERTY('Edition') AS [Edition],
            SERVERPROPERTY('ProductVersion') AS [ProductVersion],
Left(@@Version, Charindex('-', @@version) - 2) As VersionName



Change Recovery Model
---------------------
USE [master]
GO
ALTER DATABASE [Mydb] SET RECOVERY SIMPLE WITH NO_WAIT
GO


Get Recovery Info
-----------------
SELECT name, recovery_model_desc 
   FROM sys.databases 
      WHERE name in ('Mydb')
 
 
 
Shrink Files
---------------

USE [Mydb]
GO
DBCC SHRINKFILE (N'mydb_log' , 0, TRUNCATEONLY)
GO


Update Column uppercase
------------------------

update [MyDB].[myTable].[HostNameCountry]
set hostname=upper(hostname)



database Size
--------------


IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
    DROP TABLE #space

CREATE TABLE #space (
      database_id INT PRIMARY KEY
    , data_used_size DECIMAL(18,2)
    , log_used_size DECIMAL(18,2)
)

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = STUFF((
    SELECT '
    USE [' + d.name + ']
    INSERT INTO #space (database_id, data_used_size, log_used_size)
    SELECT
          DB_ID()
        , SUM(CASE WHEN [type] = 0 THEN space_used END)
        , SUM(CASE WHEN [type] = 1 THEN space_used END)
    FROM (
        SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
        FROM sys.database_files s
        GROUP BY s.[type]
    ) t;'
    FROM sys.databases d
    WHERE d.[state] = 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

EXEC sys.sp_executesql @SQL

SELECT
      d.database_id
    , d.name
    , d.state_desc
    , d.recovery_model_desc
    , t.total_size
    , t.data_size
    , s.data_used_size
    , t.log_size
    , s.log_used_size
    , bu.full_last_date
    , bu.full_size
    , bu.log_last_date
    , bu.log_size
FROM (
    SELECT
          database_id
        , log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
    FROM sys.master_files
    GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
LEFT JOIN (
    SELECT
          database_name
        , full_last_date = MAX(CASE WHEN [type] = 'D' THEN backup_finish_date END)
        , full_size = MAX(CASE WHEN [type] = 'D' THEN backup_size END)
        , log_last_date = MAX(CASE WHEN [type] = 'L' THEN backup_finish_date END)
        , log_size = MAX(CASE WHEN [type] = 'L' THEN backup_size END)
    FROM (
        SELECT
              s.database_name
            , s.[type]
            , s.backup_finish_date
            , backup_size =
                        CAST(CASE WHEN s.backup_size = s.compressed_backup_size
                                    THEN s.backup_size
                                    ELSE s.compressed_backup_size
                        END / 1048576.0 AS DECIMAL(18,2))
            , RowNum = ROW_NUMBER() OVER (PARTITION BY s.database_name, s.[type] ORDER BY s.backup_finish_date DESC)
        FROM msdb.dbo.backupset s
        WHERE s.[type] IN ('D', 'L')
    ) f
    WHERE f.RowNum = 1
    GROUP BY f.database_name
) bu ON d.name = bu.database_name
ORDER BY t.total_size DESC


Get size of db from back up file
--------------------------------


-- give the path of backup file
RESTORE FILELISTONLY FROM DISK = N'C:\DB_Backup\Mydb.bak'



Link Server Query
----------------

-- get the details of the linkservers
sp_linkedservers



-- query from link server
-- below is the example
select * from openquery(LInkServerName, 'select * from XXXX.XXV_V')



Session Precheck / any active sessions for DB
---------------------------------------------

BEGIN TRANSACTION
SET NOCOUNT ON
BEGIN
DECLARE @V_COUNT INTEGER

SELECT @V_COUNT = count(*) FROM MASTER..SYSPROCESSES P, MASTER..SYSDATABASES D WHERE P.DBID = D.DBID AND D.DBID = DB_ID('#DBNAME#') and P.SPID <> @@spid and P.SPID > 50;

IF (@V_COUNT > 0)
BEGIN
SELECT SPID,hostname FROM MASTER..SYSPROCESSES P, MASTER..SYSDATABASES D
WHERE P.DBID = D.DBID AND D.DBID = DB_ID('#DBNAME#') and P.SPID <> @@spid;
RAISERROR('',16,1)
ROLLBACK TRANSACTION
RETURN
END
END


Add user
---------

USE [master]
GO
CREATE LOGIN [NEXA\username] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
GO
USE [Mydb]
GO
CREATE USER [NEXA\username] FOR LOGIN [NEXA\username]
GO
USE [Mydb]
GO
EXEC sp_addrolemember N'db_owner', N'NEXA\username'
GO


Check Performance and kill running Scripts
------------------------------------------

sp_who2

kill 74


Shrink DB
------------------


USE [MyDB]
GO
/****** Object:  StoredProcedure [mydb].[Nexa_Shrink_MyDBTrasactionLog]    Script Date: 9/27/2016 12:00:58 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [MyDB].[Nexa_Shrink_MyDBTrasactionLog] 
 
AS 
 
BEGIN 
 -- Declare required variables. 
 DECLARE @vcDBMirroringStatus VARCHAR (100); 
 DECLARE @vcMirroringStatus VARCHAR (100); 
 DECLARE @intDBId INT; 
 
 -- Set the values for variables. 
 
 SET @vcMirroringStatus = 'SYNCHRONIZED' -- This is the syncronized status 
 SET @intDBId = DB_ID();-- This is the digite mirroring DB id. 
 
 -- Get the Digite DB mirroring status 
 SET @vcDBMirroringStatus = (select mirroring_state_desc from sys.database_mirroring where database_id = @intDBId) 
 
 -- If Digite DB mirroring status is 'SYNCHRONIZED' only shrink the DB log 
 IF @vcDBMirroringStatus = @vcMirroringStatus 
 BEGIN 
  CHECKPOINT 
  BACKUP LOG  MyDb to disk = 'C:\ShrinkDBLogs\Mydb1.trn' 
  DBCC SHRINKFILE (Mydb_log, 15360) 
 END 
 
END 




-------------


SELECT TOP 25
dm_mid.database_id AS DatabaseID,
dm_migs.avg_user_impact*(dm_migs.user_seeks+dm_migs.user_scans) Avg_Estimated_Impact,
dm_migs.last_user_seek AS Last_User_Seek,
OBJECT_NAME(dm_mid.OBJECT_ID,dm_mid.database_id) AS [TableName],
'CREATE INDEX [IX_' + OBJECT_NAME(dm_mid.OBJECT_ID,dm_mid.database_id) + '_'
+ REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.equality_columns,''),', ','_'),'[',''),']','') +
CASE
WHEN dm_mid.equality_columns IS NOT NULL AND dm_mid.inequality_columns IS NOT NULL THEN '_'
ELSE ''
END
+ REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.inequality_columns,''),', ','_'),'[',''),']','')
+ ']'
+ ' ON ' + dm_mid.statement
+ ' (' + ISNULL (dm_mid.equality_columns,'')
+ CASE WHEN dm_mid.equality_columns IS NOT NULL AND dm_mid.inequality_columns IS NOT NULL THEN ',' ELSE
'' END
+ ISNULL (dm_mid.inequality_columns, '')
+ ')'
+ ISNULL (' INCLUDE (' + dm_mid.included_columns + ')', '') AS Create_Statement
FROM sys.dm_db_missing_index_groups dm_mig
INNER JOIN sys.dm_db_missing_index_group_stats dm_migs
ON dm_migs.group_handle = dm_mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details dm_mid
ON dm_mig.index_handle = dm_mid.index_handle
WHERE dm_mid.database_ID = DB_ID()
ORDER BY Avg_Estimated_Impact DESC
GO



---------------------------------







Thursday, August 2, 2018

Some Useful SQL queries for MSSQL

 1.Check the Recovery model of the databases





Monday, June 25, 2018

Parser error in IIS in viewing reports


Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load file or assembly 'Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.




Assembly Load Trace: The following information can be helpful to determine why the assembly 'Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].




Issue : missing report viewer

Solution : Download installation package from below link and install.


Below Thread gives more information



Wednesday, June 20, 2018

SQL server check the status of the shrink

I have shrink database using SQL server Management Studio visual editor.

Right click database --> tasks --> Shrink --> database

Window comes and shows shrink is running. But this has been there for more than one day. So i need to check the status of the shrinking.



with below script you will get list of the commands and its status, completed percentage etc. look for command DbccFilesCompact , you will get all the details.

--------------------------------------------------------------------------------------------------

SELECT percent_complete, start_time, status, command, estimated_completion_time, cpu_time, total_elapsed_time
FROM sys.dm_exec_requests

----------------------------------------------------------------------------------------------------

As above  may give a little too large list, you can put a cross apply and get a better output as below script


----------------------------------------------------------------------------------------------------

select T.text, R.Status, R.Command, DatabaseName = db_name(R.database_id)
       , R.cpu_time, R.total_elapsed_time, R.percent_complete
from   sys.dm_exec_requests R
       cross apply sys.dm_exec_sql_text(R.sql_handle) T
order by Command

----------------------------------------------------------------------------------------------------



When i query, status was shown as "suspended".
I tried to cancel job by clicking window close button, but did not work.
So i restarted the db server and shrink the log file using the script.


----------------------------------------------------------------------------------------------------

USE [myDb]
GO
DBCC SHRINKFILE (N'myDB_log' , 0, TRUNCATEONLY)
GO

----------------------------------------------------------------------------------------------------


'myDB_log' is the logical name for the log file for the database 'myDB'

Monday, June 18, 2018

Stop Transaction Logs from Growing on a SQL Server

Problem: In a SQL server, you may have seen most of the time space becomes zero due to growth of the log.

Solution: In SQL Server, database transaction log keeps growing until you take a backup of the database. Once taken backup, log files will be truncate. It is not logical to delete transaction log files until you take a backup of the database ( mostly for production class database servers, for test environment transaction logs may not important as production).

Why ?

In a situation, database corruption or loss, you can recreate the database with restoring last database backup and restoring transaction logs on top of that with no loss.

(This is why database files and log files should be in different disks)

But in a test environment ( Other than production ) it is preferred to be automatically truncate the log files which will help to reduce the space used by the database. SQL server let us do this by changing the recovery model.

Set the recovery model = Simple

How to do 

Open SQL server Management studio --> select database --> Right click and select Properties --> Go to Option --> Change "recovery model" to Simple

you can do it in script using below

USE [master]
GO
ALTER DATABASE [myDB] SET RECOVERY SIMPLE WITH NO_WAIT
GO

You can check model with below script

SELECT name, recovery_model_desc 
   FROM sys.databases 
      WHERE name = 'myDB' ;


If Log files has grown, better to shrink after changing the recovery type.


Monday, March 26, 2018

Select = date without timestamp with sql

you may have a data for date column with timestamp
eg: 2018-03-26 13:40:22.470

let's say you need to check the date eg: 2018-03-26

Then you need to take part of the date string. you have various options, here i use convert()

 select count(*)
  -- convert(varchar(10),LastErrorOccurredDate,120)
 from Mytable (nolock)
 where convert(varchar(10),LastErrorOccurredDate,120) ='2018-03-26'

Friday, January 26, 2018

Error in creating Microsoft SQL server connection

Error:
Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library

This is the basic error and this will have a full stack trace.
When creating database connection, you must have enabled the "integratedSecurity=true".
This will enable LDAP users to access the database.

Solution :



1.goto: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated
2. Download the JDBC file and extract to your preferred location
3.open the auth folder matching your OS x64 or x86
4. copy sqljdbc_auth.dll file and paste in: C:\Program Files\Java\jdk_version\bin
restart either eclipse or netbeans

In a case when you do not have permission to copy the files to folders.
set thi as a VM argument
In eclipse

1) Create a folder 'sqlauth' in your C: drive, and copy the dll file sqljdbc_auth.dll to the folder
2) Go to Run> Run Configurations
3) Choose the 'Arguments' tab for your class
4) Add the below code in VM arguments:
         -Djava.library.path="C:\\sqlauth"
5) Hit 'Apply' and click 'Run'

https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated
https://blogs.msdn.microsoft.com/jdbcteam/2017/03/31/jdbc-download-center-pages-and-repackaging/



Tuesday, January 23, 2018

Get the queries run by a users

USE master
go
SELECT sdest.DatabaseName
    ,sdes.session_id
    ,sdes.[host_name]
    ,sdes.[program_name]
    ,sdes.client_interface_name
    ,sdes.login_name
    ,sdes.login_time
    ,sdes.nt_domain
    ,sdes.nt_user_name
    ,sdec.client_net_address
    ,sdec.local_net_address
    ,sdest.ObjName
    ,sdest.Query
FROM sys.dm_exec_sessions AS sdes
INNER JOIN sys.dm_exec_connections AS sdec ON sdec.session_id = sdes.session_id
CROSS APPLY (
    SELECT db_name(dbid) AS DatabaseName
        ,object_id(objectid) AS ObjName
        ,ISNULL((
                SELECT TEXT AS [processing-instruction(definition)]
                FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
                FOR XML PATH('')
                    ,TYPE
                ), '') AS Query

    FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
    ) sdest
where sdes.session_id <> @@SPID
--and sdes.nt_user_name = '' -- Put the username here !
--ANd login_name ='user'
ORDER BY sdec.session_id

Thursday, January 11, 2018

Always on group database fails. May be not accessible or recovery mode. This may due to some incident happened in the database server.

1.       Always on group database fails. May be not accessible or recovery mode. This may due to some incident happened in the database server.

Soution: set online database from primary database. Eg: let’s say you have two servers and each server has two availability groups. Server1 has availGroup1 as primary and server2 has availGroup2 as primary. The database ‘myDB’ has failed and it’s a member of availGroup2. AvailGroup2 resides in server2 and try to bring the ‘myDB’ online in server2.

ALTER DATABASE MyDB SET ONLINE

If you execute this in other server, you might get the error as

-----------------------------------------------------
Msg 5052, Level 16, State 1, Line 2
ALTER DATABASE is not permitted while a database is in the Restoring state.
Msg 5069, Level 16, State 1, Line 2

ALTER DATABASE statement failed.
---------------------------------------------------------

Give little time. Server2, MyDb will come online.
After MyDB comes online add database to the AvailGroup2 from the server2 and connect with the MyDb in the server1.




Sunday, December 4, 2016

Microsoft SQL server - Find size of the Log files

Below script will help you to find the size of the log files in your db (data file,log file etc)
you can put the name of the database replacing "yourDb"
and if you need to get all the files details of the all the databases, just omit the filter where caluse


SELECT DB_NAME(database_id) AS DatabaseName,
Name AS Logical_Name,
Physical_Name, (size*8)/1024 SizeMB
FROM sys.master_files
WHERE DB_NAME(database_id) = 'yourDb'
GO


Thursday, November 3, 2016

SQL Server :Link Server Test connection fail

Issue:
I have created a link server in MS SQL server.
Connect to database with "windows  Auhtentication"  - Connection successful
Conneect to database server with " SQL server Auhtentication -  Test connection fail

most proabably you will get an error like below


Cannot create an instance of OLE DB provider "OraOLEDB.Oracle" for linked server "YourLinkServerName". (Microsoft SQL Server, Error: 7302)

Solution
Enable "Allow inprocess" to "OraOLEDB.Oracle"

How to do this
---------

Server Objects --> Linked Servers -->Providers --> OraOLEDB.Oracle


tick Enable "Allow inprocess"

make sure you have link server using this provider



Friday, October 21, 2016

Microsoft SQL server - Restore dates

It's handy stuff if you can find the refresh dates of a database. All details are inside db server and it's a matter of finding the correct query.

Below query will help to get the required information on refresh/ db restoration


SELECT [rs].[destination_database_name], 
[rs].[restore_date], 
[bs].[backup_start_date], 
[bs].[backup_finish_date], 
[bs].[database_name] as [source_database_name], 
[bmf].[physical_device_name] as [backup_file_used_for_restore]
FROM msdb..restorehistory rs
INNER JOIN msdb..backupset bs
ON [rs].[backup_set_id] = [bs].[backup_set_id]
INNER JOIN msdb..backupmediafamily bmf 
ON [bs].[media_set_id] = [bmf].[media_set_id] 
ORDER BY [rs].[restore_date] DESC


Friday, September 23, 2016

Copying logins from one Sql server to another SQL server 2012

when you restoring data base you may need to copy the users also. sql server gives a easy way of scripting out this process using two sps.

  • sp_help_revlogin 
  • sp_hexadecimal

Steps:

  1. create two sps. naming " sp_help_revlogin " and "sp_hexadecimal "
  2. script out the user details by running "sp_help_revlogin"
    1.       exec sp_help_revlogin
  3. If you need to run only for specific user run sp with user name.
    1.      exec sp_help_revlogin 'Alex'
  4. once you run scripts , you will get the script to be run on the other server. It's just a matter of copying it and run on the server you need to create/copy users 

For more information refer below links
https://support.microsoft.com/en-us/kb/918992
https://support.microsoft.com/en-us/kb/246133


Below are the script for two sps


-------------------------------start script----------------------------------------------------------------


USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
  DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
    @binvalue varbinary(256),
    @hexvalue varchar (514) OUTPUT
AS
DECLARE @charvalue varchar (514)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
  DECLARE @tempint int
  DECLARE @firstint int
  DECLARE @secondint int
  SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
  SELECT @firstint = FLOOR(@tempint/16)
  SELECT @secondint = @tempint - (@firstint*16)
  SELECT @charvalue = @charvalue +
    SUBSTRING(@hexstring, @firstint+1, 1) +
    SUBSTRING(@hexstring, @secondint+1, 1)
  SELECT @i = @i + 1
END

SELECT @hexvalue = @charvalue
GO
 
IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
  DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary  varbinary (256)
DECLARE @PWD_string  varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr  varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)

DECLARE @defaultdb sysname
 
IF (@login_name IS NULL)
  DECLARE login_curs CURSOR FOR

      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
  DECLARE login_curs CURSOR FOR


      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name
OPEN login_curs

FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
  PRINT 'No login(s) found.'
  CLOSE login_curs
  DEALLOCATE login_curs
  RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
  IF (@@fetch_status <> -2)
  BEGIN
    PRINT ''
    SET @tmpstr = '-- Login: ' + @name
    PRINT @tmpstr
    IF (@type IN ( 'G', 'U'))
    BEGIN -- NT authenticated account/group

      SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
    END
    ELSE BEGIN -- SQL Server authentication
        -- obtain password and sid
            SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) )
        EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
        EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT
 
        -- obtain password policy state
        SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
        SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
 
            SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']'

        IF ( @is_policy_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
        END
        IF ( @is_expiration_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked
        END
    END
    IF (@denylogin = 1)
    BEGIN -- login is denied access
      SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
    END
    ELSE IF (@hasaccess = 0)
    BEGIN -- login exists but does not have access
      SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
    END
    IF (@is_disabled = 1)
    BEGIN -- login is disabled
      SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
    END
    PRINT @tmpstr
  END

  FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
   END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO
-------------------end script------------------------------------------

Friday, September 9, 2016

file types in sql server database

There are three main file types

  • MDF
  • NDF
  • LDF
MDF - Primary data file
Starting point of the database.This points to other files inside database.Every database has one primary data file.
All the data in the database objects are stored inside primary data file.(tables, stored procedures, triggers, views,....etc)


NDF - secondary data files
can have only one primary file and maintain any number of secondary data files
Optional - not necessary to have.



LDF - Log files
hold the all the log information
you can use this to recover database
size of log file depends on the log level defined by the database administrator
Should have at least one log file. ( can have multiples)

So basically you should have a primary data file and log file for each database.

mentioned extensions for the each category are optional and you can have any extension name instead of (.mdf, .ndf, .ldf) , but it is recommend to follow the standard. unless you have a necessity.






System Cannot Find the path specified - Restore database from back up file

you may have got the error "System Cannot Find the path specified " when restoring database from a back up file.
reason : sql server does not create the directory structure
solution: create the directory structure. you will get rid of the error