Posted on Leave a comment

Print out DATABASEPROPERTYEX properties


PRINT 'Collation = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'Collation') as varchar), '' )
PRINT 'Edition = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'Edition') as varchar), '' )
PRINT 'ServiceObjective = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'ServiceObjective') as varchar), '' )
PRINT 'ComparisonStyle = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'ComparisonStyle') as varchar), '' )
PRINT 'LastGoodCheckDbTime = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'LastGoodCheckDbTime') as varchar), '' )
PRINT 'LCID = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'LCID') as varchar), '' )
PRINT 'MaxSizeInBytes = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'MaxSizeInBytes') as varchar), '' )
PRINT 'Recovery = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'Recovery') as varchar), '' )
PRINT 'ServiceObjective = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'ServiceObjective') as varchar), '' )
PRINT 'ServiceObjectiveId = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'ServiceObjectiveId') as varchar), '' )
PRINT 'SQLSortOrder = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'SQLSortOrder') as varchar), '' )
PRINT 'Status = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'Status') as varchar), '' )
PRINT 'Updateability = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'Updateability') as varchar), '' )
PRINT 'UserAccess = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'UserAccess') as varchar), '' )
PRINT 'Version = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'Version') as varchar), '' )
PRINT 'IsAnsiNullDefault = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAnsiNullDefault') as varchar), '' )
PRINT 'IsAnsiNullsEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAnsiNullsEnabled') as varchar), '' )
PRINT 'IsAnsiPaddingEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAnsiPaddingEnabled') as varchar), '' )
PRINT 'IsAnsiWarningsEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAnsiWarningsEnabled') as varchar), '' )
PRINT 'IsArithmeticAbortEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsArithmeticAbortEnabled') as varchar), '' )
PRINT 'IsAutoClose = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAutoClose') as varchar), '' )
PRINT 'IsAutoCreateStatistics = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAutoCreateStatistics') as varchar), '' )
PRINT 'IsAutoCreateStatisticsIncremental = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAutoCreateStatisticsIncremental') as varchar), '' )
PRINT 'IsAutoShrink = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAutoShrink') as varchar), '' )
PRINT 'IsAutoUpdateStatistics = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsAutoUpdateStatistics') as varchar), '' )
PRINT 'IsClone = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsClone') as varchar), '' )
PRINT 'IsCloseCursorsOnCommitEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsCloseCursorsOnCommitEnabled') as varchar), '' )
PRINT 'IsFulltextEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsFulltextEnabled') as varchar), '' )
PRINT 'IsInStandBy = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsInStandBy') as varchar), '' )
PRINT 'IsLocalCursorsDefault = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsLocalCursorsDefault') as varchar), '' )
PRINT 'IsMemoryOptimizedElevateToSnapshotEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsMemoryOptimizedElevateToSnapshotEnabled') as varchar), '' )
PRINT 'IsMergePublished = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsMergePublished') as varchar), '' )
PRINT 'IsNullConcat = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsNullConcat') as varchar), '' )
PRINT 'IsNumericRoundAbortEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsNumericRoundAbortEnabled') as varchar), '' )
PRINT 'IsParameterizationForced = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsParameterizationForced') as varchar), '' )
PRINT 'IsQuotedIdentifiersEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsQuotedIdentifiersEnabled') as varchar), '' )
PRINT 'IsPublished = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsPublished') as varchar), '' )
PRINT 'IsRecursiveTriggersEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsRecursiveTriggersEnabled') as varchar), '' )
PRINT 'IsSubscribed = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsSubscribed') as varchar), '' )
PRINT 'IsSyncWithBackup = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsSyncWithBackup') as varchar), '' )
PRINT 'IsTornPageDetectionEnabled = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsTornPageDetectionEnabled') as varchar), '' )
PRINT 'IsVerifiedClone = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsVerifiedClone') as varchar), '' )
PRINT 'IsXTPSupported = ' + isnull(cast(DATABASEPROPERTYEX('mydb', 'IsXTPSupported') as varchar), '' )
Posted on Leave a comment

query AD with Hex ObjectGUID

In Powershell:

get-aduser -LDAPFilter "(&(objectClass=user)(objectGUID=\02\8B\28\AF\48\4F\32\4A\88\B6\0D\B1\30\57\82\F3))"

In Transact-SQL

SELECT *
FROM OPENQUERY(ADSI,'SELECT cn, ADsPath FROM ''LDAP://DC=myDC,DC=myDC2'' WHERE objectGUID=''\02\8B\28\AF\48\4F\32\4A\88\B6\0D\B1\30\57\82\F3'' ')

Posted on Leave a comment

Creating a linked server for SQL Server Always On Listener

Here’s some examples for creating linked server connection to an Always On Availability Group listener

–IF USING INTEGRATED SECURITY

EXEC master.dbo.sp_addlinkedserver @server = N’MY_LINKEDSERVER’
,@srvproduct = N’SQL’
,@provider = N’SQLNCLI11′
,@datasrc = N’MY_LISTENER’
,@provstr = N’Provider=SQLNCLI11;Server=MY_LISTENER;Database=MY_DBNAME;Integrated Security=SSPI;ApplicationIntent=ReadOnly;MultiSubnetFailover=True;’
,@catalog = N’MY_DBNAME’
GO

EXEC master.dbo.sp_serveroption @server=N’MY_LINKEDSERVER’, @optname=N’connect timeout’, @optvalue=N’63’
GO

–IF USING SQL LOGIN SECURITY

EXEC master.dbo.sp_addlinkedserver @server = N’MY_LINKEDSERVER’
,@srvproduct = N’SQL’
,@provider = N’SQLNCLI11′
,@datasrc = N’MY_LISTENER’
,@provstr = N’Provider=SQLNCLI11;Server=MY_LISTENER;Database=MY_DBNAME;ApplicationIntent=ReadOnly;MultiSubnetFailover=True;’
,@catalog = N’MY_DBNAME’
GO

EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N’MY_LINKEDSERVER’,@useself=N’False’,@locallogin=NULL,@rmtuser=N’MY_SQLLOGIN’,@rmtpassword=’MY_SQLPASSWORD’
GO

EXEC master.dbo.sp_serveroption @server=N’MY_LINKEDSERVER’, @optname=N’connect timeout’, @optvalue=N’63’
GO

Posted on Leave a comment

WordPress Asking for FTP Credentials when Adding/Updating/Deleting Plug-Ins

If WordPress detects that it is running under a different process than the owner of the file, it will prompt for FTP connection information. If you do not have access to chown, or perform other methods of fixing this, here are two that can be implemented if all you have is FTP and write access on your wp-config.php file.

1) Locate your WordPress root diectory and find the wp-config.php file. Edit the file and insert this somewhere in the middle as it’s own block, normally put it after the
mysql username/password block.

/*** FTP login settings ***/
define("FTP_HOST", "localhost");
define("FTP_USER", "yourftpusername");
define("FTP_PASS", "yourftppassword");

2) Another option is to define FS_METHOD in your wp-config.php file. This bypasses WordPress’s recurring prompts, and allows auto-updates of your files to happen.

Open /Wp-Config.Php Paste the following code to your wp-config.php file, preferably just below every other line of code.

define('FS_METHOD','direct');
Posted on Leave a comment

Database Suspect Mode

1. Run a checkdb

DBCC CHECKDB ([db_name_here]) WITH ALL_ERRORMSGS, DATA_PURITY, EXTENDED_LOGICAL_CHECKS

2. Ensure there is enough free disk space for the data files and transaction log files to grow.

3. Check SQL Server and Windows event logs to see if can determine when corruption started, any errors or events that may have contributed to corruption, when last restart of instance, last online of database, I/O interruptions, power outages, etc. If “under the gun” to get db back online, this step may have to be performed post-mortem.

4. Attempt repair

EXEC sp_resetstatus 'db_name_here';
 ALTER DATABASE [db_name_here] SET EMERGENCY
 DBCC CHECKDB('db_name_here')
 ALTER DATABASE [db_name_here] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
 DBCC CHECKDB('db_name_here', REPAIR_REBUILD)
 ALTER DATABASE [db_name_here] SET MULTI_USER

5. If REPAIR_REBUILD does not fix it and data loss is a concern, then make copies of the *.ldf, *.mdf, and *.ndf files.

You can then attempt to restore the database from last good backups and transaction log backups up to the point of corruption, or attempt a REPAIR_ALLOW_DATA_LOSS

EXEC sp_resetstatus 'db_name_here';
 ALTER DATABASE [db_name_here] SET EMERGENCY
 DBCC CHECKDB('db_name_here')
 ALTER DATABASE [db_name_here] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
 BACKUP DATABASE [db_name_here] TO DISK = N'R:\backup_path_here\db_name_here.bak'
 DBCC CHECKDB('db_name_here', REPAIR_ALLOW_DATA_LOSS)
 ALTER DATABASE [db_name_here] SET MULTI_USER

6. If possible, can try restarting instance. If not possible to restart instance due to causing other DB outages, then attempt to offline database, then set back online. Sometimes suspect mode is due to a problem during the on-lining of the db and a second attempt to online db clears up suspect issue. Of course, in extreme cases, attempting this may result in the database not being able to online at all…

7. Once you do get it back online run a checkdb and a full backup

DBCC CHECKDB ([db_name_here]) WITH ALL_ERRORMSGS, DATA_PURITY, EXTENDED_LOGICAL_CHECKS

 BACKUP DATABASE [db_name_here] TO DISK = N'R:\backup_path_here\db_name_here.bak'

NOTE: See the suspect database a lot on EXPRESS editions and databases with AUTO_CLOSE enabled. If this is the case then sometimes the database does not “open” properly and reports as suspect. You can clear the suspect by offline then online the database. When it is back online, recommend turning the AUTO_CLOSE off.

Posted on Leave a comment

Powershell: Generate DDL for list of database objects


#******************************************************************
# POWERSCRIPT FILE NAME: getddl.ps1
# Scripts out DDL for given list of database objects
#******************************************************************
set-strictmode -version Latest;
#set-strictmode -off;

######USER PROVIDED VALUES#######
$SERVER_NAME = "MYSERVERNAME\MYINST";             #INSTANCE NAME
$DATABASE_NAME = "master";                        #DATABASE NAME
$OBJ_LIST = ('sysobjects','sp_who');              #PROVIDE LIST OF OBJECT NAMES IN ARRAY, EXAMPLE
#$OBJ_LIST = Get-Content "C:\temp\objects.txt";   #PROVIDE LIST OF OBJECT NAMES IN TEXT FILE, ONE ENTRY PER LINE
$OUT_PATH = "C:\temp";                            #OUTPUT FOLDER, MUST ALREADY EXIST


##GLOBAL VARIABLES##
$C_OK = 0;    # 0 for OK exit status
$C_NOTOK = 1; # Non-Zero for NOT-OK exit status


function main()
{
   $retstat = $C_OK;

   $tstamp = timestamp;
   write-host "$tstamp starting up";

   #connection string
   $CONN_STRING = "Server=$SERVER_NAME;Database=$DATABASE_NAME;Trusted_Connection=True";

   #initialize connection objects
   $SqlConn = New-Object System.Data.SQLClient.SQLConnection;
   $SqlConn.ConnectionString = $CONN_STRING;
   $SqlCmd = New-Object System.Data.SQLClient.SQLCommand;
   $SqlCmd.Connection = $SqlConn;

   #define command
   $SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure;
   $SqlCmd.CommandText = 'sp_helptext';

   #define parameters
   $SqlCmd.Parameters.Add("@objname",[system.data.SqlDbType]::NVarChar) | out-Null;
   $SqlCmd.Parameters['@objname'].Direction = [system.data.ParameterDirection]::Input;

    
   try
   {
      $tstamp = timestamp;
      write-host "$tstamp connecting to $CONN_STRING";
      $SqlConn.Open();

      $tstamp = timestamp;
      write-host "$tstamp processing records";
      $n = 0;

      foreach ($obj in $OBJ_LIST)
      {
         $SqlCmd.Parameters['@objname'].value = clnStr $obj;
           
         #cmdToString $SqlCmd; ##output SQL command 
         $rs = $SqlCmd.ExecuteReader();

         $outfile = "$OUT_PATH\$obj.sql";

         $tstamp = timestamp;
         write-host "$tstamp Collecting $obj";

         $s = '';
         while ($rs.Read())
         {
            $s += $rs.GetValue(0);
         }
         $rs.Close();
         $rs.Dispose();

         $tstamp = timestamp;
         write-host "$tstamp Writing $outfile";
         $sw = new-object system.IO.StreamWriter($outfile);
         $sw.write($s);
         $sw.close();

         $n++;
      }#foreach
    
      $SqlCmd.Dispose();
      $SqlConn.Close();
      $SqlConn.Dispose();    

      $tstamp = timestamp;
      write-host "$tstamp processed $n objects";
   }
   catch
   {
      $line = $_.InvocationInfo.ScriptLineNumber
      $e = $_.Exception
      Write-Host -ForegroundColor Red "Exception: $e at line $line"
      #echo $_.Exception|format-list -force;  ##verbose error message
      $retstat = $C_NOTOK;
      cmdToString $SqlCmd;
   }
   
   $tstamp = timestamp;
   write-host "$tstamp shutting down";    
   exit $retstat;
}#main()


function timestamp()
{
   return($(get-date -F "yyyyMMdd_HHmmss"));
}#timestamp()



function clnStr( $val )
{
   if ( $($val) -eq $null )
   {
      $ret = [System.DBNull]::Value;
   }
   else
   {
      $ret = $val.toString().replace("'","''");
   }
   return($ret);
}#clnStr()



function cmdToString($cmd)
{
   $c = " ";
   $s = "EXEC " + $cmd.CommandText;
   foreach ($p in $cmd.Parameters)
   {
      $s += $c + $p.ParameterName;
      if ( $p.Value.Equals([DBNull]::Value) )
      {
         $s += " = NULL";
      }
      else
      {
         $s += " = '" + $p.Value + "'";
      }
      $c = ", ";
   }
   write-host $s;
}#cmdToString()


clear;
main;

Posted on Leave a comment

Matching SQL Agent Jobs to SSRS Subscriptions

Run this query on the instance hosting your SSRS databases to get list of SSRS subscriptions and their corresponding SQL Agent job names.


   SELECT b.[name] "JobName"
        , e.[name] "ReportName"
        , e.[path] "ReportPath"
        , d.[description] "SubscriptionDescription"
        , a.SubscriptionID
        , laststatus
        , eventtype
        , LastRunTime
        , date_created
        , date_modified
     FROM ReportServer.dbo.ReportSchedule a 
     JOIN msdb.dbo.sysjobs b
       ON cast(a.ScheduleID as varchar(1000)) = b.[name]
     JOIN ReportServer.dbo.ReportSchedule c
       ON a.ScheduleID = c.ScheduleID
     JOIN ReportServer.dbo.Subscriptions d
       ON c.SubscriptionID = d.SubscriptionID
     JOIN ReportServer.dbo.[Catalog] e
       ON d.report_oid = e.itemid

This can be useful if you need to explicitly execute the subscription directly from SQL or need to customize the SQL Agent job in some way such as preventing the report from being run based on conditions that cannot be defined in SSRS subscription manager.

Posted on Leave a comment

Sharepoint and Auto-Create statistics

Sharepoint has built-in statistics that are optimized for how Sharepoint works.

For SharePoint 2010 it is not recommended to Auto-Create statistics for any databases.  Auto-Update statistics can be enabled for content databases if you are not manually updating statistics and you are experiencing performance issues.

For SharePoint 2013, enabling Auto-Create Statistics and Auto-Update Statistics is NOT supported.

https://docs.microsoft.com/en-us/SharePoint/administration/best-practices-for-sql-server-in-a-sharepoint-server-farm

Posted on Leave a comment

Reset Windows Stored Credentials

If you need to reset your saved your credentials to access the share folder from your PC you can delete those credentials by opening a command prompt running as administrator.

Then type the command:

rundll32.exe keymgr.dll, KRShowKeyMgr

You can then delete the stored credentials used to authenticate the share folder path on your local pc.

You can then try to access that share folder path and it should prompt you for the account user name and password again.