Feeds:
Posts
Comments

In my earlier article, I posted a solution how to calculate weekdays between weekends. Today I came across a situation where I need to calculate the weekends between two dates and the criterion is that weekend can be any day (not necessary Sunday only) of the week.

Given below is the function that calculates the weekends between two dates including the dates provided as input parameter. In some parts of the world weekends are on ‘Fridays’, ‘Saturdays’ and in other parts ‘Saturdays’ and ‘Sundays’.
In this function, you need to pass weekend as a parameter.

CREATE FUNCTION dbo.GetWeekendDays
( @StartDate DATETIME,
@EndDate DATETIME ,
@Weekend VARCHAR(50)
)
RETURNS INT
BEGIN

DECLARE @Xml AS XML
DECLARE @WEEKEND_DAYS AS INT
SET @Xml =CAST(('<a>'+replace(@Weekend,',' ,'</a><a>')+'</a>') AS XML)

;WITH N1 (n) AS (SELECT 1 UNION ALL SELECT 1),
N2 (n) AS (SELECT 1 FROM N1 AS X, N1 AS Y),
N3 (n) AS (SELECT 1 FROM N2 AS X, N2 AS Y),
N4 (n) AS (SELECT ROW_NUMBER() OVER(ORDER BY X.n)
FROM N3 AS X, N3 AS Y)

SELECT @WEEKEND_DAYS=SUM(1) FROM n4
WHERE DATEADD(day,n-1,@startdate)<=@Enddate
AND DATENAME(dw,DateAdd(day,n-1,@startdate)) In (
SELECT A.value('.', 'varchar(max)') as [Column]
FROM @Xml.nodes('A') AS FN(A)
)

RETURN @WEEKEND_DAYS
END
GO
SELECT dbo.GetWeekendDays
('02/01/2013','02/28/2013','Saturday,Sunday')
as [Weekend Days]

GO
SELECT dbo.GetWeekendDays
('02/01/2013','02/28/2013','Friday,Saturday')
as [Weekend Days]

--OUTPUT
Weekend Days
------------
8

(1 row(s) affected)

Weekend Days
------------
8

(1 row(s) affected)

Have a better solution ?

Invalid data type %.*ls in function %.*ls. is one of the new error messages in SQL Server 2012. This error message is related to PARSE function, a new conversion function shipped with SQL Server 2012.

Let’s discuss this in detail:
Message Number: 10761 

Severity : 15

Error Message: Invalid data type %.*ls in function %.*ls.

Error Generation:

Given below is the script that I tried to execute but it resulted with the following error :

SELECT PARSE(GETDATE() AS varchar(11)  USING 'en-US') AS Result;
--OUTPUT

Msg 10761, Level 15, State 2, Line 1
Invalid data type varchar in function PARSE.

Ooopps…… I am unable to execute it.

Resolution:
In the above example, I tried to parse a datetime into a varchar. First of all, I checked the syntax of PARSE function but the syntax is perfectly fine but the problem is, I used the wrong data type and that datatype is not compatible with the PARSE function.

Here is the list of compatible data types (Numeric & datetime data types) that you can use with this function.

Lets rewrite the above statement with the compatible data types using PARSE function. Given below is the script.

SELECT PARSE('2013-07-12' AS datetime USING 'en-US') AS Result;
--OUTPUT

Result
———————–
2013-07-12 00:00:00.000

(1 row(s) affected)

Conclusion :
Whenever you use PARSE function, make sure that you are using the compatible data type (Numeric & datetime data types) in it.

Memory Optimized Table is a new concept introduced in SQL Server Hekaton. Memory optimized table is also a table but the major difference between memory-optimized tables and disk based tables is that the memory optimized table information is available in the memory and it does not require the pages to be read into cache from disk. The performance of memory optimized table is much higher than disk based table. Shall discuss its performance in the upcoming article.

Let me create the memory optimized table, but before proceeding with the creating memory table, we should know that whenever you create memory optimized table the database must have memory-optimized data filegroup.
Lets first create a database having memory-optimized data filegroup. Given below is the script.

CREATE DATABASE Sample_DB
ON
PRIMARY(NAME = [Sample_DB],
FILENAME = 'C:\DATA\Sample_data.mdf', size=500MB)
,FILEGROUP [hekaton_demo_fg] CONTAINS MEMORY_OPTIMIZED_DATA(
NAME = [hekaton_demo_dir],
FILENAME = 'C:\DATA\Sample_dir')
LOG ON (name = [hekaton_demo_log]
, Filename='C:\DATA\Sample_log.ldf', size=500MB)
;
GO

Once you create the database having memory-optimized data filegroup then you can create memory optimized table. Given below is the script.

USE Sample_DB
GO
CREATE TABLE tbl_sample
(
[ID] INT NOT NULL PRIMARY KEY NONCLUSTERED HASH
WITH (BUCKET_COUNT = 100000),
[Name] VARCHAR(50) NOT NULL
) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA)
GO

Whenever we copy data from SQL Server to excel, we usually face some formatting issues in excel. Specially, if you copy date field from SQL Server to excel. Given below is the script and screen image.

USE AdventureWorks2012
GO
SELECT * FROM [HumanResources].[Department]
GO
--Copy the result set of the above query and paste into excel.

formattingdateinexcel1.1

Let me explain the solution step by step.

Step 1 :
Execute the query and paste the data from result set to excel.

USE AdventureWorks2012
GO
SELECT * FROM [HumanResources].[Department]
GO
--Copy the result set of the above query and paste into excel.

formattingdateinexcel1.1

Step 2 :
Once you paste the data in excel, just select the date column field, right click on it and select format cells.. from the pop up menu as shown in the picture.

formattingdateinexcel1.3

Step 3 :
Once you are in the format cells.. dialogue box, you can select the category as a date and whatever type you want you can select. Given below is the screen image.

formattingdateinexcel1.4

Step 4 :
Press OK once you are done and your date column will be formatted as shown in the picture below.

formattingdateinexcel1.5

Note : I used SQL Server 2005 & Excel 2007 to demonstrate this problem and its solution.

Let me know if you know a better solution.

In the earlier versions of SQL Server, whenever you need to rebuild an index (pass DDL statement for an online index), you sometimes end up with deadlock situation. Given below is the script that we use to rebuild an online index in the earlier version of SQL Server.

USE AdventureWorks2012
GO
ALTER INDEX ALL ON Production.Product
REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON,
STATISTICS_NORECOMPUTE = ON);

In SQL Server Hekaton, a solution to this problem has been introduced namely WAIT_AT_LOW_PRIORITY . It allows DBA to control the locking mechanism that is required to rebuild an online index and causing deadlock situations.
Given below is the script :

USE AdventureWorks2012
GO
ALTER INDEX ALL ON Production.Product
REBUILD WITH
(
FILLFACTOR = 80,
SORT_IN_TEMPDB = ON,
STATISTICS_NORECOMPUTE = ON,
ONLINE = ON ( WAIT_AT_LOW_PRIORITY
( MAX_DURATION = 4 MINUTES, ABORT_AFTER_WAIT = BLOCKERS ) ),
DATA_COMPRESSION = ROW
)
;

In the above script, you can see two arguments MAX_DURATION and ABORT_AFTER_WAIT. Given below are the details.

MAX_DURATION :
It describes the waiting time in minutes, but you can just pass the integer number and MINUTES can be removed from the syntax.

ABORT_AFTER_WAIT:
ABORT_AFTER_WAIT came up with three nice options. It basically provides you the hands on the different locking mechanism. Given below are the details :

NONE : It implements no locking on the online index rebuild operation,it performs operation like a normal scenario.
Given below is the script if you would like to implement NONE in ABORT_AFTER_WAIT.

USE AdventureWorks2012
GO
ALTER INDEX ALL ON Production.Product
REBUILD WITH
(
FILLFACTOR = 80,
SORT_IN_TEMPDB = ON,
STATISTICS_NORECOMPUTE = ON,
ONLINE = ON ( WAIT_AT_LOW_PRIORITY
( MAX_DURATION = 0 MINUTES, ABORT_AFTER_WAIT = NONE ) ),
DATA_COMPRESSION = ROW
)
;

SELF: It aborts the online index rebuild operation by using normal priority. It gives priority to the user operation instead of rebuilding index.
Given below is the script if you intend to implement SELF.

USE AdventureWorks2012
GO
ALTER INDEX ALL ON Production.Product
REBUILD WITH
(
FILLFACTOR = 80,
SORT_IN_TEMPDB = ON,
STATISTICS_NORECOMPUTE = ON,
ONLINE = ON ( WAIT_AT_LOW_PRIORITY
( MAX_DURATION = 4 MINUTES, ABORT_AFTER_WAIT = SELF) ),
DATA_COMPRESSION = ROW
)
;

BLOCKERS: It kills all the user transactions that usually block the online index rebuilding, so that you can rebuild index easily. This is not recommended if you are using at the peak hours.
Given below is the script if you would like to implement BLOCKERS.

USE AdventureWorks2012
GO
ALTER INDEX ALL ON Production.Product
REBUILD WITH
(
FILLFACTOR = 80,
SORT_IN_TEMPDB = ON,
STATISTICS_NORECOMPUTE = ON,
ONLINE = ON ( WAIT_AT_LOW_PRIORITY
( MAX_DURATION = 4 MINUTES, ABORT_AFTER_WAIT = BLOCKERS) ),
DATA_COMPRESSION = ROW
)
;

Let me know if you implement it in CTP 1 and find any issues.

Whenever new technology steps in, we usually run for its sample database to test it features, functionality & enhancement, etc. When I started testing SQL Server Hekaton, I was looking for some sample databases. Finally, I grabbed it from msdn but there, it is script only. So you need to copy and execute it but if you need a downloadable version, you can download it from here (Northwind database).

Note : Make sure you have data folder in c: drive (C:\data)

Recently, I was working on SQL Server 2014 CTP 1 and doing my usual research, and came across the new system objects shipped with CTP 1.

Given below is the list of new system objects :

S.No

 Object Name

Object Type

1

 sp_set_cardinality_estimation_model_110

EXTENDED STORED PROCEDURE

2

 plan_persist_query_text

INTERNAL TABLE

3

 plan_persist_query

INTERNAL TABLE

4

 plan_persist_plan

INTERNAL TABLE

5

 plan_persist_runtime_stats

INTERNAL TABLE

6

 plan_persist_runtime_stats_interval

INTERNAL TABLE

7

 plan_persist_context_settings

INTERNAL TABLE

8

 fn_dump_dblog_xtp

INLINE TABLE VALUED FUNCTION

9

 fn_dblog_xtp

INLINE TABLE VALUED FUNCTION

10

 fn_hadr_is_primary_replica

SCALAR FUNCTION

11

 sp_MSalreadyhavegeneration

STORED PROCEDURE

12

 sp_xtp_merge_checkpoint_files

STORED PROCEDURE

13

 sp_db_enable_clustered_columnstores

STORED PROCEDURE

14

 sp_cci_tuple_mover

STORED PROCEDURE

15

 syscsrowgroups

SYSTEM TABLE

16

 dm_resource_governor_resource_pool_volumes

VIEW

17

 dm_xtp_transaction_stats

VIEW

18

 dm_xe_database_session_event_actions

VIEW

19

 dm_xtp_gc_stats

VIEW

20

 dm_db_xtp_index_stats

VIEW

21

 dm_xe_database_session_object_columns

VIEW

22

 dm_os_buffer_pool_extension_configuration

VIEW

23

 dm_db_xtp_object_stats

VIEW

24

 dm_db_xtp_table_memory_stats

VIEW

25

 dm_xtp_consumer_memory_usage

VIEW

26

 dm_io_cluster_shared_volumes

VIEW

27

 dm_db_xtp_memory_consumers

VIEW

28

 dm_db_xtp_checkpoint

VIEW

29

 dm_xtp_threads

VIEW

30

 dm_db_merge_requests

VIEW

31

 dm_xtp_transaction_recent_rows

VIEW

32

 dm_db_xtp_checkpoint_files

VIEW

33

 dm_xtp_system_memory_consumers

VIEW

34

 dm_xe_database_session_events

VIEW

35

 dm_xtp_memory_stats

VIEW

36

 dm_db_xtp_hash_index_stats

VIEW

37

 dm_xe_database_sessions

VIEW

38

 dm_xe_database_session_targets

VIEW

39

 dm_db_xtp_gc_cycle_stats

VIEW

40

 dm_xtp_gc_queue_stats

VIEW

41

 dm_db_xtp_transactions

VIEW

42

 column_store_row_groups

VIEW

43

 hash_indexes

VIEW

44

 event_sessions

VIEW

45

 event_session_targets

VIEW

46

 event_session_fields

VIEW

47

 event_session_events

VIEW

48

 event_session_actions

VIEW

Columnstore index is one of the nice features introduced in SQL Server 2012. It improves the performance more times than the normal query but on the other hand it has some limitations as well, and one of the limitation is that you cannot create a CLUSTERED Columnstore index.

Let me demonstrate it in SQL Server 2012.

USE tempdb
GO
CREATE TABLE tbl_Product_Master
(
[Product ID] INT,
[Product Name] NVARCHAR(100),
[Model] INT
)
GO
CREATE CLUSTERED COLUMNSTORE INDEX
[IX_tbl_Product_Master_ColumnStore]
ON [tbl_Product_Master] ([Product ID])
GO
--OUTPUT

Msg 35338, Level 15, State 1, Line 3
Clustered columnstore index is not supported.

Ooopps…… I am unable to create it in SQL Server 2012.

The above limitation has been eliminated in SQL Server 2014 and you can add the CLUSTERED COLUMNSTORE INDEX in the table.

Let me demonstrate the same example in SQL Server 2014.


USE tempdb
GO
CREATE TABLE tbl_Product_Master
(
[Product ID] INT,
[Product Name] NVARCHAR(100),
[Model] INT
)
GO

CREATE CLUSTERED COLUMNSTORE INDEX
[IX_tbl_Product_Master_ColumnStore]
ON [tbl_Product_Master]
GO
--OUTPUT

Command(s) completed successfully.

Lets check whether the index has been created successfully or not.

columnstoreindexcusteredindex1.1

The result is evident above, in SQL 2014.

Let me know if you explore the other nice enhancements of SQL Server 2014.

An invalid value was specified for argument ‘%.*ls’ for the given data type  is one of the new error messages in SQL Server 2012. This error message is related to Sequence object, a new database feature shipped with SQL Server 2012.

Lets discuss this in detail:
Message Number: 11708

Severity : 16

Error Message: An invalid value was specified for argument ‘%.*ls’ for the given data type.

Error Generation:

Given below is the script that I tried to execute but it resulted with the following error.

Use AdventureWorks2012
GO
CREATE SEQUENCE [dbo].[Seq_sample]
AS [tinyint]
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 256
NO CACHE
GO

Msg 11708, Level 16, State 1, Line 1
An invalid value was specified for argument ‘MAXVALUE’ for the given data type.

Ooopps…… I am unable to execute it.

Resolution:
The issue is quite simple. I created the sequence object using tinyint data type and range of tinyint data type is from 0 to 255 as per MSDN. But if you observe carefully, in my above example, the maximum value of sequence object is 256 and that is more than the tinyint data type maximum range (255).

Lets rewrite the script and correct the maximum value range. It must be less than or equal to the defined data type range.

Use AdventureWorks2012
GO
CREATE SEQUENCE [dbo].[Seq_sample]
AS [tinyint]
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 255
NO CACHE
GO

Conclusion :
Remember, whenever you create the sequence object always keep the minimum and maximum value within the range of the data type.

Let me know if you have a better solution.

In my earlier article, I had discussed about new features of SQL Server 2014. Those features are very exciting and I was waiting for the CTP. Now, CTP 1 is available for download.

Given below are the few instructions that you should follow to install CTP 1.

  • The machine should not have any earlier versions of SQL Server.
  • There is no upgrade / side by side installation available in this CTP.
  • This CTP is only available for X64 architecture.

System requirement for SQL Server 2014 is available here.

Let me know if you face any issues with the installation.