working on it ...

Filters

Explore Public Snippets

Sort by

Found 430 snippets matching: logical

    public by sjschmalfeld  3307  9  5  2

    Rename Logical Name Database SQL Server

    Changes the logical name of a database
    // Enter here the actual content of the snippet.            
    
    -- Rename logical names (only needed if restoring from a backup for a Different database):
    ALTER DATABASE MyDatabase 
    MODIFY FILE (NAME = 'OrigDatabase_Data', NEWNAME = 'MyDatabase_data')
    GO
    ALTER DATABASE MyDatabase 
    MODIFY FILE (NAME = 'OrigDatabase_Log', NEWNAME = 'MyDatabase_log')
    GO                        

    public by cghersi  3364  3  6  4

    Change the location of MS SQL Server database files

    When you start playing with serious DB, one of the most important parts is to place (if possible) the files in different drives (physical, not only logical partitions!!!). But what if you already have your DB in production with tons of data on the same location? This script helps in solving the issue. It should be executed in three steps: 1) p
    -- 1) Execute this first chunk to put the DB offline
    ALTER DATABASE MyDBName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    ALTER DATABASE MyDBName SET OFFLINE;
    ALTER DATABASE MyDBName MODIFY FILE 
    (
       Name = MyDBName_Data,
       Filename = 'D:\DB\MyDBName.mdf'
    );
    
    ALTER DATABASE MyDBName MODIFY FILE 
    (
       Name = MyDBName_Log, 
       Filename = 'D:\DBLog\MyDBName_log.ldf'
    );
    
    ALTER DATABASE MyDBName MODIFY FILE 
    (
       Name = MyDBName_Idx, 
       Filename = 'E:\DBIndex\MyDBName_log.ndf'
    );
    
    -- 2) Manually move the files in the right location
    
    -- 3) Execute this second chunk to put the DB online
    ALTER DATABASE my SET ONLINE;
    
    ALTER DATABASE my SET MULTI_USER;

    public by cghersi  3166  1  7  1

    Find worst SQL performing queries

    You might have seen a number of queries which provides you with top 10 or top 5 worst performing queries either by Logical IO’s or by CPU time or by Elapsed Time.. I have similar query but it does many more thing. I personally do not query either by total logical reads or total cpu time or total elapsed time individually. I usually use this quer
    with PerformanceMetrics
    as
    (
    select
    --dest.text,
    --statement_start_offset,
    --statement_end_offset,
    --LEN(dest.text) ln,
    substring
    (
    dest.text,
    statement_start_offset/2,
    case when statement_end_offset = -1 then LEN(dest.text)
    else statement_end_offset
    end /2
    ) as 'Text of the SQL' ,
    deqs.plan_generation_num as 'Number of times the plan was generated for this SQL',
    execution_count as 'Total Number of Times the SQL was executed',
    DENSE_RANK() over(order by execution_count desc) as 'Rank of the SQL by Total number of Executions',
    total_elapsed_time/1000 as 'Total Elapsed Time in ms consumed by this SQL',
    DENSE_RANK() over(order by total_elapsed_time desc) as 'Rank of the SQL by Total Elapsed Time',
    Max_elapsed_time/1000 as 'Maximum Elapsed Time in ms consumed by this SQL',
    min_elapsed_time/1000 as 'Minimum Elapsed Time in ms consumed by this SQL',
    total_elapsed_time/1000*nullif(execution_count,0) as 'Average Elapsed Time in ms consumed by this SQL',
    DENSE_RANK() over(order by total_elapsed_time/nullif(execution_count,0) desc) as 'Rank of the SQL by Average Elapsed Time',
    total_worker_time as 'Total CPU Time in ms consumed by this SQL',
    DENSE_RANK() over(order by total_worker_time desc) as 'Rank of the SQL by Total CPU Time',
    Max_worker_time as 'Maximum CPU Time in ms consumed by this SQL',
    min_worker_time as 'Minimum CPU Time in ms consumed by this SQL',
    total_worker_time/nullif(execution_count,0) as 'Average CPU Time in ms consumed by this SQL',
    DENSE_RANK() over(order by total_worker_time/nullif(execution_count,0) desc) as 'Rank of the SQL by Average CPU Time',
    total_logical_reads as 'Total Logical Reads Clocked by this SQL',
    DENSE_RANK() over(order by total_logical_reads desc) as 'Rank of the SQL by Total Logical reads',
    Max_logical_reads as 'Maximum Logical Reads Clocked by this SQL',
    min_logical_reads as 'Minimum Logical Reads Clocked by this SQL',
    total_logical_reads/nullif(execution_count,0) as 'Average Logical Reads Clocked by this SQL',
    DENSE_RANK() over(order by total_logical_reads/nullif(execution_count,0) desc) as 'Rank of the SQL by Average Logical reads',
    total_physical_reads as 'Total Physical Reads Clocked by this SQL',
    DENSE_RANK() over(order by total_physical_reads desc) as 'Rank of the SQL by Total Physical Reads',
    Max_physical_reads as 'Maximum Physical Reads Clocked by this SQL',
    min_physical_reads as 'Minimum Physical Reads Clocked by this SQL',
    total_physical_reads/nullif(execution_count,0) as 'Average Physical Reads Clocked by this SQL',
    DENSE_RANK() over(order by total_physical_reads/nullif(execution_count,0) desc) as 'Rank of the SQL by Average Physical Reads',
    total_logical_writes as 'Total Logical Writes Clocked by this SQL',
    DENSE_RANK() over(order by total_logical_writes desc) as 'Rank of the SQL by Total Logical Writes',
    Max_logical_writes as 'Maximum Logical Writes Clocked by this SQL',
    min_logical_writes as 'Minimum Logical Writes Clocked by this SQL',
    total_logical_writes/nullif(execution_count,0) as 'Average Logical Writes Clocked by this SQL',
    DENSE_RANK() over(order by total_logical_writes/nullif(execution_count,0) desc) as 'Rank of the SQL by Average Logical Writes',
    deqp.query_plan as 'Plan of Query'
    --similarly you can add the ranks for maximum values as well.That is quite useful in finding some of the perf issues.
    from
    sys.dm_exec_query_stats deqs
    /*F0C6560A-9AD1-448B-9521-05258EF7E3FA*/ --use a newid so that we could exclude this query from the performanc emetrics output
    outer apply sys.dm_exec_query_plan(deqs.plan_handle) deqp --sometimes the plan might not be in the cache any longer.So using outer apply
    outer apply sys.dm_exec_sql_text(deqs.sql_handle) dest --Sometimes the text is not returned by the dmv so use outer apply.
    where
    dest.text not like '%F0C6560A-9AD1-448B-9521-05258EF7E3FA%'
    )
    select
    *
    from
    PerformanceMetrics
    where
    1=1
    --apply any of these where clause in any combinations or one by one..
    --and [Rank of the SQL by Average CPU Time] <= 20 --Use this to find the top N queries by avg CPU time.
    --and [Rank of the SQL by Average Elapsed Time] <= 20 --Use this to find the top N queries by avg elspsed time.
    --and [Rank of the SQL by Average Logical reads] <= 20 --Use this to find the top N queries by avg logical reads.
    --and [Rank of the SQL by Average Physical Reads] <= 20 --Use this to find the top N queries by avg physical reads.
    and [Rank of the SQL by Total CPU Time] <= 20 --Use this to find the top N queries by total CPU time.
    and [Rank of the SQL by Total Elapsed Time] <= 20 --Use this to find the top N queries by total elapsed time.
    and [Rank of the SQL by Total Logical reads] <= 20 --Use this to find the top N queries by Total Logical reads.
    and [Rank of the SQL by Total Physical Reads] <= 20 --Use this to find the top N queries by Total Physical Reads.
    and [Rank of the SQL by Total number of Executions] <= 20 --Use this to find the top N queries by Total number of Executions.
    --and [Rank of the SQL by Average Logical Writes] <= 20 --Use this to find the top N queries by Average Logical Writes.
    and [Rank of the SQL by Total Logical Writes] <= 20 --Use this to find the top N queries by Total Logical Writes.
    
    --I usually do the query by 6 rank types together Total logical reads,Total CPU time, Total Elapsed Time , Total Execution count ,Total Physical Reads and Total Logical Writes.Sometimes I exclude last two counters if i do not get any query in the output.
    --If some queries are say in top 10 in all these 6 categories then these needs to tune first...
    --But sometime you might not get any rows at all if u use these 6 categiories in that case remove one of these categories or try one by one..

    public by cghersi  1925  0  6  0

    Finding actual number of physical cpu installed

    By Rahul Singh, 2013/01/14 The Sql Server always see Logical cpu it does not distinguish between Hyperthreaded logical cpu and physical processor using the below query we can find out actual number of physical cpu installed on the server The first column represent logical processor and second column represent actual physical processor insta
    SELECT cpu_count AS Logical_CPU_Count , cpu_count / hyperthread_ratio AS Physical_CPU_Count FROM sys.dm_os_sys_info ;

    public by msdn  2334  2  7  0

    GetLogicalChildrenBreadthFirst: Retrieves all the logical children of a framework element using a breadth-first search. A visual element is assumed to be a logical child of another visual element if they are in the same namescop...

    Retrieves all the logical children of a framework element using a breadth-first search. A visual element is assumed to be a logical child of another visual element if they are in the same namescope. For performance reasons this method manually manages the queue instead of using recursion. The parent framework element. The logical chil
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Windows;
    using System.Windows.Media;
    
    /// <summary>
    /// Retrieves all the logical children of a framework element using a 
    /// breadth-first search.  A visual element is assumed to be a logical 
    /// child of another visual element if they are in the same namescope.
    /// For performance reasons this method manually manages the queue 
    /// instead of using recursion.
    /// </summary>
    /// <param name="parent">The parent framework element.</param>
    /// <returns>The logical children of the framework element.</returns>
    public static IEnumerable<FrameworkElement> GetLogicalChildrenBreadthFirst(this FrameworkElement parent)
    {
        Debug.Assert(parent != null, "The parent cannot be null.");
    
        Queue<FrameworkElement> queue =
            new Queue<FrameworkElement>(parent.GetVisualChildren().OfType<FrameworkElement>());
    
        while (queue.Count > 0)
        {
            FrameworkElement element = queue.Dequeue();
            yield return element;
    
            foreach (FrameworkElement visualChild in element.GetVisualChildren().OfType<FrameworkElement>())
            {
                queue.Enqueue(visualChild);
            }
        }
    }

    public by msdn  1514  0  6  0

    DeleteObject: The DeleteObject function deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object. After the object is deleted, the specified handle is no longer valid.

    The DeleteObject function deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object. After the object is deleted, the specified handle is no longer valid. A handle to a logical pen, brush, font, bitmap, region, or palette. If the function succeeds, the return value is nonzero. If t
    using System;
    using System.Runtime.InteropServices;
    
    /// <summary>
    /// The DeleteObject function deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object. After the object is deleted, the specified handle is no longer valid.
    /// </summary>
    /// <param name="hObject">A handle to a logical pen, brush, font, bitmap, region, or palette.</param>
    /// <returns>If the function succeeds, the return value is nonzero. If the specified handle is not valid or is currently selected into a DC, the return value is zero.</returns>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1414:MarkBooleanPInvokeArgumentsWithMarshalAs", Justification = "Adding this attribute causes an error."), DllImport("gdi32.dll")]
    internal static extern bool DeleteObject(IntPtr hObject);

    public by msdn  1258  0  5  0

    TraceStopLogicalOperation: Stops actual logical operation in trace repository

    Stops actual logical operation in trace repository
    /// <summary>
    /// Stops actual logical operation in trace repository
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2135:SecurityRuleSetLevel2MethodsShouldNotBeProtectedWithLinkDemandsFxCopRule"),
    SecurityPermission(SecurityAction.LinkDemand)]
    static public void TraceStopLogicalOperation()
    {
        try
        {
            System.Diagnostics.Trace.CorrelationManager.StopLogicalOperation();
        }
        catch (InvalidOperationException)
        {
            //stack empty
        }
    }

    public by msdn  1044  2  7  0

    TraceStartLogicalOperation: Starts logical operation in trace repository

    Starts logical operation in trace repository
    #endregion
    
    #region Public Methods
    
    /// <summary>
    /// Starts logical operation in trace repository
    /// </summary>
    /// <param name="operationName"></param>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2135:SecurityRuleSetLevel2MethodsShouldNotBeProtectedWithLinkDemandsFxCopRule"),
    SecurityPermission(SecurityAction.LinkDemand)]
    static public void TraceStartLogicalOperation(string operationName)
    {
        if (String.IsNullOrEmpty(operationName))
            throw new ArgumentNullException("operationName","Trace message is null or empty string");
    
        System.Diagnostics.Trace.CorrelationManager.ActivityId = Guid.NewGuid();
        System.Diagnostics.Trace.CorrelationManager.StartLogicalOperation(operationName);
    }

    public by msdn  2773  3  6  0

    CreateVirtualHardDisk: Creates a VHD or VHDX.

    Creates a VHD or VHDX. The name of the server on which to perform the action. The path to the VHD/VHDX to create. The path to the parent VHD/VHDX. The type for the new VHD/VHDX. The format of the new VHD/VHDX. The size of the new VHD/VHDX. The block size of the new VHD/VHDX. The logical sector size of the new VHD/VHDX. The physical sec
    /// <summary>
    /// Creates a VHD or VHDX.
    /// </summary>
    /// <param name="ServerName">The name of the server on which to perform the action.</param>
    /// <param name="VirtualHardDiskPath">The path to the VHD/VHDX to create.</param>
    /// <param name="ParentPath">The path to the parent VHD/VHDX.</param>
    /// <param name="Type">The type for the new VHD/VHDX.</param>
    /// <param name="Format">The format of the new VHD/VHDX.</param>
    /// <param name="FileSize">The size of the new VHD/VHDX.</param>
    /// <param name="BlockSize">The block size of the new VHD/VHDX.</param>
    /// <param name="LogicalSectorSize">The logical sector size of the new VHD/VHDX.</param>
    /// <param name="PhysicalSectorSize">The physical sector size of the new VHD/VHDX.</param>
    internal static void
    CreateVirtualHardDisk(
        string ServerName,
        string VirtualHardDiskPath,
        string ParentPath,
        VirtualHardDiskType Type,
        VirtualHardDiskFormat Format,
        Int64 FileSize,
        Int32 BlockSize,
        Int32 LogicalSectorSize,
        Int32 PhysicalSectorSize)
    {
        ManagementScope scope =
            new ManagementScope("\\\\" + ServerName + "\\root\\virtualization\\v2");
    
        VirtualHardDiskSettingData settingData =
            new VirtualHardDiskSettingData(
                Type,
                Format,
                VirtualHardDiskPath,
                ParentPath,
                FileSize,
                BlockSize,
                LogicalSectorSize,
                PhysicalSectorSize);
    
        using (ManagementObject imageManagementService =
            StorageUtilities.GetImageManagementService(scope))
        {
            using (ManagementBaseObject inParams =
                imageManagementService.GetMethodParameters("CreateVirtualHardDisk"))
            {
                inParams["VirtualDiskSettingData"] =
                    settingData.GetVirtualHardDiskSettingDataEmbeddedInstance(
                        ServerName,
                        imageManagementService.Path.Path);
    
                using (ManagementBaseObject outParams = imageManagementService.InvokeMethod(
                    "CreateVirtualHardDisk", inParams, null))
                {
                    WmiUtilities.ValidateOutput(outParams, scope);
                }
            }
        }
    }

    external by ??? ???  159  0  2  0

    Add only with logical operation for general

    Add only with logical operation for general: AddLogical.java
    public class AddLogical {
        public static void main(String[] args) {
            int a = 231;
            int b = 35;
            System.out.printf("%d + %d = %d%n", a, b, a + b);
            while(b != 0){
                int c = a ^ b;
                b = (a & b) << 1;
                a = c;
            }
            System.out.println(a);
                    
        }
    }
    
    
    
    • Public Snippets
    • Channels Snippets