European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

SQL Server 2014 Hosting Italy - HostForLIFE.eu :: How to Apply IDENTITY Column with SQL Server Memory Optimized Table?

clock February 3, 2015 06:33 by author Peter

In this article, I want to explain you about How to Apply IDENTITY Column with SQL Server Memory Optimized Table. Memory Optimized tables were introduced in SQL Server 2014. As we know, memory optimized tables don't support an IDENTITY column. thus however will we produce an INDENTITY (auto incremented) column with a memory optimized table?

And here is the example code:
CREATE TABLE IdentityTest
(
        ID INTEGER IDENTITY(1,1) NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 100000),
        Name VARCHAR(50) not null
)
WITH (MEMORY_OPTIMIZED = ON)


And this is the result:
Msg 10771, Level 16, State 7, Line 2
The feature ‘identity column’ is not yet implemented with memory optimized tables.

The workaround of an IDENTITY value is to use a SEQUENCE object. A SEQUENCE object (introduced with SQL Server 2012) works equally to an IDENTITY value with massive scope to the IDENTITY. The SEQUENCE object isn't restricted to a column or table however it's scoped to a whole information. one among the benefits of a SEQUENCE object is, it is controlled by application code additionally. This SEQUENCE is shared with multiple tables.

Apply IDENTITY Column with SQL Server Memory Optimized Table
To apply an IDENTITY column in a memory optimized table, you must use a SEQUENCE object. The following are the steps to use a SEQUENCE object as an IDENTITY column with a memory optimized table.

Step 1
Create a memory optimized table and a SEQUENCE object.
--Create memory optimized table
CREATE TABLE IdentityTest
(
        ID INTEGER NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 100000),
         Name VARCHAR(50) not null
)
WITH (MEMORY_OPTIMIZED = ON)
--Create SEQUENCE object
CREATE SEQUENCE [dbo].[TableNextId]
AS [int]
             START WITH 1000
              INCREMENT BY 1
              MINVALUE  1
              MAXVALUE 10000

Step 2
Use a SEQUENCE object to get following Id using the “NEXT value FOR” operate. SQL Server writes a replacement value within the value in the SEQUENCE to the system table whenever the next value FOR function is called. thus we will catch on filled like an IDENTITY column.
DECLARE @nextId INTEGER = NEXT VALUE FOR [dbo].[TableNextId]]
INSERT INTO IdentityTest VALUES (@nextId, 'my Test')

A memory optimized table doesn't support an IDENTITY (auto incremented) column. however using a SEQUENCE object, we will get an auto incremented value for a numeric data type column.

HostForLIFE.eu SQL Server 2014 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



SQL Server 2014 Hosting Belgium - HostForLIFE.eu :: How to Calculate Total Rows Inserted per Second ?

clock January 29, 2015 06:31 by author Peter

In this tutorial, I will write an article about How to Calculate Total Rows Inserted per Second in SQL Server 2014. Ever expected to compute the quantity of columns embedded consistently, for each table in every database on a server? Alternately, have you ever expected to approve that all methods have quit keeping in touch with tables? These sorts of inquiries come up routinely for me. To help with this, I've composed the following script, which inspects metadata qualities utilizing sys.partitions. This system isn't as precise as running SELECT COUNT(*) FROM, however its much quicker.

Remember, since it’s just looking at row counts, its very little help on tables that have a considerable measure of update/delete  action. Yet it does what I need it to do, and I utilize it pretty frequently, so I thought I'd experience case any other individual can advantage from it as well.

/* Declare Parameters */
DECLARE @newBaseline BIT = 1 -- change to 0 when you don't want to replace the baseline, i.e. after initial run
  , @delay CHAR(8) = '00:00:30'; -- change as needed 
IF @newBaseline = 1
BEGIN
    IF OBJECT_ID('tempdb..#baseline') IS NOT NULL
        DROP TABLE #baseline; 
    CREATE TABLE #baseline
    (
         database_name  SYSNAME
       , table_name     SYSNAME
       , table_rows     BIGINT
       , captureTime    DATETIME NULL
    );
END 

IF OBJECT_ID('tempdb..#current') IS NOT NULL
    DROP TABLE #current;
 CREATE TABLE #current
(
     database_name  SYSNAME
   , table_name     SYSNAME
   , table_rows     BIGINT
   , captureTime    DATETIME NULL
); 
IF @newBaseline = 1
BEGIN
    EXECUTE sp_MSforeachdb 'USE ?;
        INSERT INTO #baseline
        SELECT DB_NAME()
            , o.name As [tableName]
            , SUM(p.[rows]) As [rowCnt]
            , GETDATE() As [captureTime]
        FROM sys.indexes As i
        JOIN sys.partitions As p
            ON i.[object_id] = p.[object_id]
           AND i.index_id  = p.index_id
        JOIN sys.objects As o
            ON i.[object_id] = o.[object_id]
        WHERE i.[type] = 1
        GROUP BY o.name;' 
    WAITFOR DELAY @delay;
END
 EXECUTE sp_MSforeachdb 'USE ?;
INSERT INTO #current
SELECT DB_NAME()
    , o.name As [tableName]
    , SUM(p.[rows]) As [rowCnt]
    , GETDATE() As [captureTime]
FROM sys.indexes As i
JOIN sys.partitions As p
    ON i.[object_id] = p.[object_id]
   AND i.index_id  = p.index_id
JOIN sys.objects As o
    ON i.[object_id] = o.[object_id]
WHERE i.[type] = 1
GROUP BY o.name;' 
SELECT  c.*
      , c.table_rows - b.table_rows AS 'new_rows'
      , DATEDIFF(second, b.captureTime, c.captureTime) AS 'time_diff'
      , (c.table_rows - b.table_rows) / DATEDIFF(second, b.captureTime, c.captureTime) AS 'rows_per_sec'
FROM #baseline AS b
JOIN #current AS c
    ON b.table_name = c.table_name
   AND b.database_name = c.database_name
ORDER BY new_rows DESC;

HostForLIFE.eu SQL Server 2014 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



SQL Server 2014 Hosting Russia - HostForLIFE.eu :: Restart Interrupted Restore Operations

clock January 8, 2015 07:19 by author Peter

Circumstances in which a restore operation is hindered are not exceptionally remarkable. This is the reason, in this post, we will demonstrate to you what you need to do with a specific end goal to restart the interrupted operation using T-SQL queries in SQL Server 2014.

In the event that your restore operation was interrupted, you can at present restart the methodology and proceed starting there where it got intruded.

This is a peculiarity that can be extremely valuable in the event that you have huge databases which you need to restore. On the off chance that the methodology of restoring falls flat near to the end, the majority of the times you can restart the whole operation from the point where it cleared out off, as opposed to restarting the whole restore procedure of the database.

To be particular, when you make your restore from tape, you can restart from the current tape as opposed to restarting from the first. Anyhow, if the restore was in the stage when it was being rolled forward, then no information will be replicated from that backup set.

Restart interrupted restore with T-SQL
In the event that you have utilized a T-SQL query to restore your database and the methodology was hindered for any reason, known or obscure, then what you need to do is to define a RESTART proviso toward the end of the same inquiry and run the question yet again.

Let’s assume that you have the following query, or something similar, and it got interrupted during execution.
-- Restore a full database backup of myDB database
RESTORE DATABASE myDB
FROM DISK = 'C:\myDB.bak'
GO

Presently, keeping in mind the end goal to proceed with and interrupted restore operations, connected for our situation, we are going to utilize the query from above completed with the WITH RESTART clause.

-- Just run the initial RESTORE statement specifying WITH RESTART in order to restart interrupted restore operations
RESTORE DATABASE myDB
FROM DISK = 'C:\myDB.bck'
WITH RESTART
GO



SQL Server 2014 Hosting Spain - HostForLIFE.eu :: How to Check Fragmentation in SQL Server ?

clock December 9, 2014 07:48 by author Peter

When you have performance problems in your MSSQL database, one of the first thing you must to verify is that the fragmentation. When the fragmentation is high, SQL Server has got the chance to both reorganize or rebuild indexes. You are able to detect index fragmentation by making use of Dynamic Management View (DMV) sys.dm_db_index_physical_stats and verify the avg_fragmentation_in_percent column.

Use [MyDB];
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS a
   JOIN sys.indexes AS b ON a.object_id = b.object_id
AND a.index_id = b.index_id
ORDER BY avg_fragmentation_in_percent DESC;


When the value avg_fragmentation_in_percent in among 5% and 30% you ought to perform a reorganize of your indexes, not really a total rebuild. A rebuild you simply need invoked when the fragmentation percentage is more than 30%. No action ought to be taken when the fragmentation proportion is lower than 5% and that is a standard level of fragmentation.

The code below can rebuild all indexes with default fill factor:
Use [MyDB];
EXEC sp_MSforeachtable
  @command1="print '?'",
  @command2="ALTER INDEX ALL ON ? REBUILD WITH (ONLINE=OFF)"

Hope this code will helps you!

 



SQL Server 2014 Hosting Netherlands - HostForLIFE.eu :: Index Unused Script in SQL Server

clock December 4, 2014 05:52 by author Peter

As the majority of you will know, an index can enhance the performance of the query most of the time ; internally sql server has to carry out lots of function to keep these indexes in SQL Server 2014. When I started a brand new occupation, I arrived to discover lots of indexes were developed for a few in our production tables. Thus I made a decision to get yourself a script which returns the indexes that’s not active.


Note : it uses the dmv’s so, this isn't a fairly accurate query. However you could use this like a start and apply reasonable just before running the drop index statement.
SELECT  DB_NAME() AS database_name ,
        S.name AS [schema_name] ,
        O.name AS [object_name] ,
        C.name AS column_name ,
        I.name AS index_name ,
        ( CASE WHEN I.is_disabled = 1 THEN 'Yes'
                ELSE 'No'
           END ) AS [disabled] ,
        ( CASE WHEN I.is_hypothetical = 1 THEN 'Yes'
                ELSE 'No'
            END ) AS hypothetical ,
        rows = (SELECT SUM(p.rows) FROM sys.partitions p WHERE p.index_id = i.index_id
                        AND p.object_id = i.object_id GROUP BY p.index_id, p.OBJECT_ID),
        N'USE ' + DB_NAME() + N'; DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(s.name) +
                    '.' + QUOTENAME(OBJECT_NAME(i.OBJECT_ID)) AS 'drop statement'
FROM    [sys].[indexes] I
       INNER JOIN [sys].[objects] O ON O.[object_id] = I.[object_id]
                                       AND O.[type] = 'U'
                                        AND O.is_ms_shipped = 0
                                        AND O.name <> 'sysdiagrams'
        INNER JOIN [sys].[tables] T ON T.[object_id] = I.[object_id]
        INNER JOIN [sys].[schemas] S ON S.[schema_id] = T.[schema_id]
        INNER JOIN [sys].[index_columns] IC ON IC.[object_id] = I.[object_id]
                                                AND IC.index_id = I.index_id
        INNER JOIN [sys].[columns] C ON C.[object_id] = IC.[object_id]
                                        AND C.column_id = IC.column_id
WHERE   I.[type] > 0
        AND I.is_primary_key = 0
        AND I.is_unique_constraint = 0
        AND NOT EXISTS ( SELECT *
                            FROM   [sys].[index_columns] XIC
                                INNER JOIN [sys].[foreign_key_columns] FKC ON FKC.parent_object_id =
IC.[object_id]
                                                    AND FKC.parent_column_id = XIC.column_id
                            WHERE  XIC.[object_id] = I.[object_id]
                               AND XIC.index_id = I.index_id )
        AND NOT EXISTS ( SELECT *
                            FROM   [master].[sys].[dm_db_index_usage_stats] IUS
                            WHERE  IUS.database_id = DB_ID(DB_NAME())
                                AND IUS.[object_id] = I.[object_id]
                                AND IUS.index_id = I.index_id )



European SQL 2014 Hosting - UK :: How to Join The First Row in SQL

clock August 14, 2014 12:41 by author Onit

To easily making report, we need a list of users and the most recent widget each user has created. We have a users table and a widgets table, and each user has many widgets. users.id is the primary key on users, and widgets.user_id is the corresponding foreign key in widgets.

To solve this problem, we need to join only the first row. There are several ways to do this. Here are a few different techniques and when to use them.

Use Correlated Subqueries when the foreign key is indexed

Correlated subqueries are subqueries that depend on the outer query. It's like a for loop in SQL. The subquery will run once for each row in the outer query:

select * from users join widgets on widgets.id = (
    select id from widgets
    where widgets.user_id = users.id
    order by created_at desc
    limit 1
)

Notice the where widgets.user_id = users.id clause in the subquery. It queries the widgets table once for each user row and selects that user's most recent widget row. It's very efficient if user_id is indexed and there are few users.

Use a Complete Subquery when you don't have indexes

Correlated subqueries break down when the foreign key isn't indexed, because each subquery will require a full table scan.

In that case, we can speed things up by rewriting the query to use a single subquery, only scanning the widgets table once:

select * from users join (
    select distinct on (user_id) * from widgets
    order by user_id, created_at desc
) as most_recent_user_widget
on users.id = most_recent_user_widget.user_id

This new subquery returns a list of the most recent widgets, one for each user. We then join it to the users table to get our list.

We've used Postgres' DISTINCT ON syntax to easily query for only one widget peruser_id.

Use Nested Subqueries if you have an ordered ID column

In our example, the most recent row always has the highest id value. This means that even without DISTINCT ON, we can cheat with our nested subqueries like this:

select * from users join (
    select * from widgets
    where id in (
        select max(id) from widgets group by user_id
    )
) as most_recent_user_widget
on users.id = most_recent_user_widget.user_id

We start by selecting the list of IDs repreenting the most recent widget per user. Then we filter the main widgets table to those IDs. This gets us the same result as DISTINCT ON since sorting by id and created_at happen to be equivalent.

Use Window Functions if you need more control

If your table doesn't have an id column, or you can't depend on its min or max to be the most recent row, use row_number with a window function. It's a little more complicated, but a lot more flexible:

select * from users join (
    select * from (
        select *, row_number() over (
            partition by user_id
            order by created_at desc
        ) as row_num
        from widgets
    ) as ordered_widgets
    where ordered_widgets.row_num = 1
) as most_recent_user_widget
on users.id = most_recent_user_widget.user_id
order by users.id

The interesting part is here:

select *, row_number() over (
    partition by user_id
    order by created_at desc
) as row_num
from widgets
over (partition by user_id order by created_at desc

specifies a sub-table, called a window, per user_id, and sorts those windows by created_at desc.row_number() returns a row's position within its window. Thus the first widget for each user_id will have row_number 1. 

In the outer subquery, we select only the rows with a row_number of 1. With a similar query, you could get the 2nd or 3rd or 10th rows instead.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in