Friday, January 29, 2016

The row was not found at the Subscriber when applying the replicated command. (Source: MSSQLServer, Error number: 20598)

I had this error:
Databases were out of sync.
Looked at links below

https://support.microsoft.com/en-us/kb/3066750
http://stackoverflow.com/questions/567597/sql-replication-row-not-found-error


Re Initialize Subscription : DID IT

Thursday, January 28, 2016

not null vs != OR <>

NULL Cannot be compared to any value using the comparison operators. NULL = NULL is false. Null is not a value. The IS operator is specially designed to handle NULL comparisons.



<> is Standard SQL-92; != is its equivalent: Both evaluate for values,
WHERE NULL CANNOT


Logins, Roles and Permissions , Sysadmins

find out what login has what role and who are sysadmins?


Step1:
SET NOCOUNT ON

CREATE TABLE #DatabaseRoleMemberShip
   (
        Username VARCHAR(100),
        Rolename VARCHAR(100),
        Databasename VARCHAR(100)
       
    )DECLARE @Cmd AS VARCHAR(MAX)DECLARE @PivotColumnHeaders VARCHAR(4000)           SET @Cmd = 'USE [?] ;insert into #DatabaseRoleMemberShip
select u.name,r.name,''?'' from sys.database_role_members RM inner join
sys.database_principals U on U.principal_id=RM.member_principal_id
inner join sys.database_principals R on R.principal_id=RM.role_principal_id
where u.type<>''R'''EXEC sp_MSforeachdb @command1=@cmd

SELECT  @PivotColumnHeaders =                        
  COALESCE(@PivotColumnHeaders + ',[' + CAST(rolename AS VARCHAR(MAX)) + ']','[' + CAST(rolename AS VARCHAR(MAX))+ ']'                    
  )                    
  FROM (SELECT DISTINCT rolename FROM #DatabaseRoleMemberShip )a ORDER BY rolename  ASC


SET @Cmd = 'select
databasename,username,'+@PivotColumnHeaders+'
from
(
select   * from #DatabaseRoleMemberShip) as p
pivot
(
count(rolename  )
for rolename in ('+@PivotColumnHeaders+') )as pvt'

--drop table #DatabaseRoleMemberShip
EXECUTE(@Cmd )      



Step2:
who are sys admins

SELECT   name,type_desc,is_disabled
FROM     master.sys.server_principals
WHERE    IS_SRVROLEMEMBER ('sysadmin',name) = 1
ORDER BY name

Wednesday, January 27, 2016

How to resolve the “The server principal “Domain\LoginName” already exists” Error Msg 15025, Level 16, State 2, Line 1



Step1: SELECT SUSER_SID( 'Domain\LoginName');
SID:0x010500000000000515000000C5F84793CB280B51AD7C2F5320370000

Step2:
Select * from sys.server_principals
where SID=0x010500000000000515000000C5F84793CB280B51AD7C2F5320370000
go

Step3:
drop login [Domain\LoginName']
go

Step4:
CREATE LOGIN [Domain\LoginName'  FROM WINDOWS WITH DEFAULT_DATABASE=[master],
DEFAULT_LANGUAGE=[us_english]
 go

Step5: If required, this is for a particular database
 USE AuditDB
 go
EXEC sp_addrolemember 'db_datareader', 'Domain\LoginName''
GO

Tuesday, January 26, 2016

SELECT Top 10 and order by Results vary every time ( different results every time i run)

EX:

Select top 100 col1, col2, col3,xyz.col4
from ABC
JOIN XYZ
Order col3


i have that query ran at 10AM and i ran the same query at 10:15am
the results were different...
Y?


Oderby Clo3 is not uinique


I had to put Unique column (PK column, INDEX Column) to get the same results everyTime

This is just my exp:
i see online some parallel processing,. ,Maxdop etc things

Monday, January 25, 2016

SQL Server – Track Database Size Growth Trend

https://sqljourney.wordpress.com/2013/02/13/sql-server-track-database-size-growth-trend/

Unlock SQL login/User with out Resetting Password


 Alter login [XYZ] with CHECK_POLICY = OFF

go

Alter login [XYZ] with CHECK_POLICY = ON

go

Backup and Restore Permissions

To Backup and Restore Database:

Create a login, add Login to Individual database  Roles,
db_backupoperator--Can Backup Database , but cannot Restore 
DB_Creator-Server Role --Can Restore database 




BACKUP
BACKUP DATABASE and BACKUP LOG permissions default to members of the sysadmin fixed server role and the db_owner and db_backupoperator fixed database roles


RESTORE
If the database being restored does not exist, the user must have CREATE DATABASE permissions to be able to execute RESTORE. If the database exists, RESTORE permissions default to members of the sysadmin and dbcreator fixed server roles and the owner (dbo) of the database (for the FROM DATABASE_SNAPSHOT option, the database always exists).

RESTORE permissions are given to roles in which membership information is always readily available to the server. Because fixed database role membership can be checked only when the database is accessible and undamaged, which is not always the case when RESTORE is executed, members of the db_owner fixed database role do not have RESTORE permissions.

Thursday, January 21, 2016

How to exit from SP with out running



EX: I have SP:

BEGIN

PRINT 'you have bad input'
RETURN

END

to exit with out running SP




BEGIN

RETURN---- the SP will exit here
PRINT 'you have bad input'

END




Wednesday, January 20, 2016

Maximum Degree of Parallelism ,Cost Of Parallelism

Maximum Degree of  Parallelism =8
Cost Of Parallelism =50

Source:BrendtOzar
https://www.youtube.com/watch?v=QkymlR4ZdIE

Wednesday, January 13, 2016

Trace Flags Info

  • TF 1118  – This trace flag switches allocations in tempdb from single-page at a time for the first 8 pages, to immediately allocate an extent (8 pages). It’s used to help alleviate allocation bitmap contention in tempdb under a heavy load of small temp table creation and deletion. As Paul Randal says, “Everyone should turn it on, on all instances of SQL Server, from SQL Server 2000 onwards. There’s no down-side to having it turned on”. In fact, for SQL Server 2016, Microsoft has now included the behavior from TF 1118 in the product by default, so you don’t need to enable it for SQL Server 2016.
  • TF 2371 – This trace flag changes the threshold for automatic statistics updates from the old default of needing 20% of the rows in a table to have been updated to trigger a statistics update to a dynamic % that decreases as the table row count increases. This means that you will get more frequent automatic statistics updates on larger tables. Even with this change, it is still a good idea to use SQL Server Agent jobs to periodically trigger manual statistics updates on your most volatile tables. Personally, I think there is no downside to having this enabled. Someone at Microsoft must agree, since for SQL Server 2016, they have now included the behavior from TF 2371 in the product by default, so you don’t need to enable it for SQL Server 2016.
  • TF 3226 – This trace flag prevents SQL Server from writing information to the SQL Server Error log after every successful database backup (which includes Full, Differential and Log backups). It will still log failed log backups, which is what you really care about anyway. Records of all database backups are still stored in the msdb system database after enabling this trace flag. Personally, I think there is no downside to having this enabled, and it makes it much easier to find more relevant information in the SQL Server Error log when this trace flag is enabled.

http://www.sqlservice.se/updated-microsoft-sql-server-trace-flag-list/

Tuesday, January 12, 2016

Find Text from SP or JOB

USE [msdb]
GO
SELECT j.job_id,
 s.srvname,
 j.name,
 js.step_id,
 js.command,
 j.enabled
FROM dbo.sysjobs j
JOIN dbo.sysjobsteps js
 ON js.job_id = j.job_id
JOIN master.dbo.sysservers s
 ON s.srvid = j.originating_server_id
WHERE js.command LIKE N'%SP text %'
--and js.command not like '%sp_send_dbmail%'

select  *
from syscomments
where text like '%abc%'
order by object_name(id)

Sunday, January 10, 2016

DBCC FULL T-log backups

I use Maintenance plan for these

DBCC-11:30
Full 12 am
T-log every 15 mins  

Update/Rebuild Statistics run every sunday 3 am

DECLARE @SQL VARCHAR(1000)
DECLARE @DB sysname

DECLARE curDB CURSOR FORWARD_ONLY STATIC FOR
   SELECT [name]
   FROM master..sysdatabases
   WHERE [name]  NOT IN ('model', 'tempdb')
   ORDER BY [name]
   
OPEN curDB
FETCH NEXT FROM curDB INTO @DB
WHILE @@FETCH_STATUS = 0
   BEGIN
       SELECT @SQL = 'USE [' + @DB +']' + CHAR(13) + 'EXEC sp_updatestats' + CHAR(13)
       PRINT @SQL

       FETCH NEXT FROM curDB INTO @DB
   END
   
CLOSE curDB
DEALLOCATE curDB
--Put the code in JOB
-- No need for creating th sp in any databases, it is already exist




 Take out put and put in as a job

Rebuild indexes ( create as SP in all DBS and run as a JOB ) every night




--Depending on fragmentation index level appropriated action will be taken (no action, rebuild or reorganize)

--If average fragmentation is less than 10% no action will be taken,
-- if average fragmentation is between 10% and 30% index will be reorganized,
-- finally if index average fragmentation is greater than 30% index will be rebuilt.

-- Ensure a USE <databasename> statement has been executed first.


SET NOCOUNT ON;
DECLARE @objectid int;
DECLARE @indexid int;
DECLARE @partitioncount bigint;
DECLARE @schemaname nvarchar(130);
DECLARE @objectname nvarchar(130);
DECLARE @indexname nvarchar(130);
DECLARE @partitionnum bigint;
DECLARE @partitions bigint;
DECLARE @frag float;
DECLARE @command nvarchar(4000);
DECLARE @dbid smallint;
-- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function
-- and convert object and index IDs to names.
SET @dbid = DB_ID();
SELECT
    [object_id] AS objectid,
    index_id AS indexid,
    partition_number AS partitionnum,
    avg_fragmentation_in_percent AS frag, page_count
INTO #work_to_do
FROM sys.dm_db_index_physical_stats (@dbid, NULL, NULL , NULL, N'LIMITED')
WHERE avg_fragmentation_in_percent > 10.0  -- Allow limited fragmentation
AND index_id > 0 -- Ignore heaps
AND page_count > 25; -- Ignore small tables
-- Declare the cursor for the list of partitions to be processed.
DECLARE partitions CURSOR FOR SELECT objectid,indexid, partitionnum,frag FROM #work_to_do;
-- Open the cursor.
OPEN partitions;
-- Loop through the partitions.
WHILE (1=1)
BEGIN
FETCH NEXT
FROM partitions
INTO @objectid, @indexid, @partitionnum, @frag;
IF @@FETCH_STATUS < 0 BREAK;
SELECT @objectname = QUOTENAME(o.name), @schemaname = QUOTENAME(s.name)
FROM sys.objects AS o
JOIN sys.schemas as s ON s.schema_id = o.schema_id
WHERE o.object_id = @objectid;
SELECT @indexname = QUOTENAME(name)
FROM sys.indexes
WHERE object_id = @objectid AND index_id = @indexid;
SELECT @partitioncount = count (*)
FROM sys.partitions
WHERE object_id = @objectid AND index_id = @indexid;
-- 30 is an arbitrary decision point at which to switch between reorganizing and rebuilding.

IF @frag < 30.0
SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REORGANIZE';
IF @frag >= 30.0
SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REBUILD';
IF @partitioncount > 1
SET @command = @command + N' PARTITION=' + CAST(@partitionnum AS nvarchar(10));
EXEC (@command);
PRINT N'Executed: ' + @command;
END

-- Close and deallocate the cursor.

CLOSE partitions;

DEALLOCATE partitions;

-- Drop the temporary table.

DROP TABLE #work_to_do;

--GO

--If average fragmentation is less than 10% no action will be taken, if average fragmentation is between 10% and 30% index will be reorganized,
-- finally if index average fragmentation is greater than 30% index will be rebuilt.
--Want a full complete solution (also a bit more complex) solution? Please check this great article provided by Ola Hallengren available at:

Check index fragmentation


Select dbschemas.[name] as 'Schema', 
dbtables.[name] as 'Table', 
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
from sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) as indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes as dbindexes on dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
where indexstats.database_id = DB_ID()
order by indexstats.avg_fragmentation_in_percent desc



Index_ID of 0 indicates the "heap" for that table.  It is where the table data is stored.  Index_ID of 1 indicates that there is a clustered index on the table.
A heap does not have a name that's why it is NULL.


I would Rebuild Indexes / Re organize indexes only if 
Avg fragmenation >10
Re organize when frag < 30.0
Re build when frag > 30.0

Page count >25
IndexID>0


Friday, January 8, 2016

Find Text from all SQL Jobs

USE [msdb]
GO
SELECT j.job_id,
s.srvname,
j.name,
js.step_id,
js.command,
j.enabled
FROM dbo.sysjobs j
JOIN dbo.sysjobsteps js
ON js.job_id = j.job_id
JOIN master.dbo.sysservers s
ON s.srvid = j.originating_server_id
WHERE js.command LIKE N'%DBMAIL%'
--and js.command not like '%sp_send_dbmail%'

Wednesday, January 6, 2016

Useful always on AG queries to find status

SELECT * from sys.dm_hadr_auto_page_repair
SELECT * from  sys.dm_hadr_cluster_networks
SELECT * from  sys.dm_hadr_availability_group_states
SELECT * from  sys.dm_hadr_database_replica_cluster_states
SELECT * from  sys.dm_hadr_availability_replica_cluster_nodes
SELECT * from  sys.dm_hadr_database_replica_states
SELECT * from  sys.dm_hadr_availability_replica_cluster_states
SELECT * from  sys.dm_hadr_instance_node_map
SELECT * from  sys.dm_hadr_availability_replica_states
SELECT * from  sys.dm_hadr_name_id_map
SELECT * from  sys.dm_hadr_cluster
SELECT * from  sys.dm_tcp_listener_states
--where type_desc like '%DATABASE_MIRRORING%'
SELECT * from  sys.dm_hadr_cluster_members



SELECT * from  sys.availability_databases_cluster
SELECT * from  sys.availability_groups_cluster
SELECT * from  sys.availability_group_listener_ip_addresses
SELECT * from  sys.availability_read_only_routing_lists
SELECT * from  sys.availability_group_listeners
SELECT * from  sys.availability_replicas
SELECT * from  sys.availability_groups

The Service Broker endpoint is in disabled or stopped state in Always on Availability Groups

SELECT is_broker_enabled, name  FROM sys.databases  

All Availability Group Databases =0
It’s a default behavior. The message will show when AlwaysOn availability group Listener is created and SQL Server binds the Listener’s IP dynamically.
There is no method to suppress the message. These messages are informational message and do not cause any harm and can safely be ignored.

https://social.technet.microsoft.com/Forums/sqlserver/en-US/bc5c8a4b-bc09-4478-8434-7d2e0d5c203f/the-service-broker-endpoint-is-in-disabled-or-stopped-state?forum=sqlgetstarted

TIP on SQL Server Profiler Trace

I was trying to find out who/ what application are connecting to  SQL SERVER  "ITSQL"
Instance Name:"ITSQL"
IP Address: "172.00.00.00"


Say, 
Application XYZ connecting to  SQL SERVER with Instance Name:"ITSQL "
and 
Application ABC  or someone else connecting to  SQL SERVER with IP Address: "172.00.00.00"



when i try to run Trace with below template 
EventClass ApplicationName LoginName SPID Starttime Database HostName SessionLoginName ServerName

i was not able to find out application which are connecting to SQL SERVER with IP Address: "172.00.00.00"


so after a lot of testing i found that even when ABC application is trying to connect with IP address  "172.00.00.00" , it shows as connecting to Instance name "ITSQL"



So, i was able to find out all connections..


Fyi...this is not proven yet in production..

Tuesday, January 5, 2016

Limit SQL Server 2014 Error logs



I have  Upgraded SQL SERVER  from 2008R2 to 2014  and all of a sudden i was seeing too much information about checkpoint, flush avg wait time etc ...in SQL Server error logs ..


I tried looking at DBCC TRACESTATUS 
i see 3502,3504 set to on ...
i turn them off like below and no more information being logged 

DBCC TRACEOFF(3504,-1 ) 
go
DBCC TRACEOFF (3502, -1); 
GO
--3502,3504 Checkpoint , flush etc

https://blog.sqlauthority.com/2009/06/27/sql-server-fix-error-17892-logon-failed-for-login-due-to-trigger-execution-changed-database-context...