Author Archives: nakulvachhrajani

Unknown's avatar

About nakulvachhrajani

Nakul Vachhrajani is a SQL Server MCTS, TOGAF certified Technical Architect with Capgemini having a total IT experience of more than 16 years. Nakul is an active blogger, and has been a guest columnist for SQLAuthority.com and SQLServerCentral.com. Nakul presented a webcast on the “Underappreciated Features of Microsoft SQL Server” at the Microsoft Virtual Tech Days Exclusive Webcast series (May 02-06, 2011) on May 06, 2011. He is also the author of a research paper on Database upgrade methodologies, which was published in a CSI journal, published nationwide. In addition to his passion about SQL Server, Nakul also contributes to the academia out of personal interest. He visits various colleges and universities as an external faculty to judge project activities being carried out by the students. Disclaimer: The opinions expressed herein are his own personal opinions and do not represent his employer’s view in anyway.

#0239 – SQL Server 2012 – Msg 402 – The data types datetime and time are incompatible in the add/subtract operator


Microsoft SQL Server 2008 came with a wide array of T-SQL enhancements. One of them was the ability to split a DATETIME value into DATE and TIME values. From a storage standpoint this allowed us to store and bind (on the UI) date and time values separately, while appending the values when displaying on a report or exporting to a 3rd party system. They are also useful to store time revisions with respect to a DATETIME value.

Here’s a quick example:

SQL Server 2008/2008 R2

In the query below, I will be taking two variables – a DATETIME and a TIME value and then add and subtract the TIME value from the DATETIME value to get the final result.

--Please execute on a SQL 2008/2008 R2 instance
USE tempdb;
GO
DECLARE @tDate DATETIME = '2013-02-11 00:00:00.000';
DECLARE @tTime TIME = '08:00:00.000';

SELECT @tDate AS DateTimeSource, 
       @tTime AS TimeSource,
       (@tDate + @tTime) AS DateTimeAddResult,
       (@tDate - @tTime) AS DateTimeSubtractResult;
GO

The output of the above query is shown below:

image

As you can see, we were able to successfully add and subtract the DATE and the TIME values to create corresponding DATETIME values.

Changes in SQL Server 2012

If your application uses code similar to the one shown above, it will not work as expected in SQL Server 2012 (SQL 11/”Denali”):

--Please execute on a SQL 2012 instance
USE tempdb;
GO
DECLARE @tDate DATETIME = '2013-02-11 00:00:00.000';
DECLARE @tTime TIME = '08:00:00.000';

SELECT @tDate AS DateTimeSource, 
       @tTime AS TimeSource,
       (@tDate + @tTime) AS DateTimeAddResult;

SELECT @tDate AS DateTimeSource, 
       @tTime AS TimeSource,
       (@tDate - @tTime) AS DateTimeSubtractResult;
GO

The following error message is encountered:

Msg 402, Level 16, State 1, Line 6

The data types datetime and time are incompatible in the add operator.

Msg 402, Level 16, State 1, Line 10

The data types datetime and time are incompatible in the subtract operator.

As you can see, SQL Server 2012 no longer allows us to add/subtract a TIME value from a DATETIME value using the conventional Add (+) and Subtract (-) operators.

Workaround

A workaround to this issue is to modify the code such that the TIME value is converted to a DATETIME value before the Add (+) or Subtract (-) operation takes place.

--Please execute on a SQL 2012 instance
USE tempdb;
GO
DECLARE @tDate DATETIME = '2013-02-11 00:00:00.000';
DECLARE @tTime TIME = '08:00:00.000';

SELECT @tDate AS DateTimeSource, 
       @tTime AS TimeSource,
       (@tDate + CAST(@tTime AS DATETIME)) AS DateTimeAddResult,
       (@tDate - CAST(@tTime AS DATETIME)) AS DateTimeSubtractResult;
GO

image

Conclusion

Between just two releases, this is a considerably major change because one may have a considerable number of objects written using this ability of DATETIME and DATE/TIME data-types to add/subtract. With an upgrade of the database to SQL Server 2012, these objects will need to be modified. I would therefore present the following questions before you:

  • Have you faced this issue in your migration from SQL Server 2008 to SQL Server 2012?
  • What solution/workaround did you apply?

Reference:

Until we meet next time,

Be courteous. Drive responsibly.

#0238-SQL Server 2012-DMVs & Catalog Views-sys.sequences


SQL Server Catalog Views & Dynamic Management Views (DMVs) take an administrator to the very heart of SQL Server. They allow administrators to carry out essential functions like monitoring, diagnostics and inventory preparations. This leads one to think that whenever a new functionality is introduced into SQL Server, corresponding DMVs and Catalog Views must either be updated and/or new ones introduced.


One of the major enhancements in SQL Server 2012 is the SEQUENCE (refer the “Further Reading” section for more information on Sequences and their usage). In this post, I will be studying the use of a related Catalog View: sys.sequences. Needless to say, this Catalog View is new to SQL Server 2012.


sys.sequences


To get started, let me create a sequence and use it to populate a result set (re-using Pinal’s example here):

USE AdventureWorks2012
GO
CREATE SEQUENCE [Seq]
AS [int]
START WITH 1
INCREMENT BY 1
MAXVALUE 20000
GO
— First Run
SELECT NEXT VALUE FOR Seq, c.CustomerID
FROM Sales.Customer c
GO

Now, I will execute the following query which fetches all records from the new Catalog View – sys.sequences.

SELECT ss.name,
ss.object_id,
ss.principal_id,
ss.schema_id,
ss.parent_object_id,
ss.type,
ss.type_desc,
ss.create_date,
ss.modify_date,
ss.is_ms_shipped,
ss.is_published,
ss.is_schema_published,
ss.start_value,
ss.increment,
ss.minimum_value,
ss.maximum_value,
ss.is_cycling,
ss.is_cached,
ss.cache_size,
ss.system_type_id,
ss.user_type_id,
ss.precision,
ss.scale,
ss.current_value,
ss.is_exhausted
FROM sys.sequences AS ss

image


As we can see from the output, this Catalog View returns one record for each sequence object in the database. Below is a detailed summary of the most important columns with respect to the values supplied in the CREATE SEQUENCE statement:



  • start_value – Value defined in the START WITH clause
  • increment – Value defined in the INCREMENT BY clause
  • minimum_value – Value defined in the MINVALUE clause
  • maximum_value – Value defined in the MAXVALUE clause
  • is_cycling – 1 if CYCLE clause has a value of 1, else 0
  • is_cached – 1 if CACHE clause has a value of 1, else 0
  • cache_size – The cache size defined during sequence creation
  • system_type_id – A sequence can be created for multiple data-types. This column returns the ID of the system type for sequence objects’ data type
  • user_type_id – This column returns the ID of the multiplied type for sequence objects’ data type
  • precision – (self-explanatory)
  • scale– (self-explanatory)
  • currrent_value– This contains the last obligated value of the sequence.
  • is_exhausted – A value of 0 means that more values can be generated from the system and that a manual re-cycle of the Sequence is not required

Further Reading:



Until we meet next time,


Be courteous. Drive responsibly.

#0237-SQL Server-Intellisense not working SQL Server 2008 R2 & Visual Studio 2010 SP1


While most would be very meticulous about ensuring that their servers are running software with the latest and greatest service/cumulative update packs. However, most developers that I have worked with only deploy a patch if their IT forces them to (via group policies and automatic deployment of updates) or if they face a challenge and the patch resolves the issue. In such a scenario, developers often come up to me and ask this question:

The Intelli-sense feature in the SQL Server Management Studio (SSMS) on my local SQL Server 2008 R2 instance stopped working. Can you fix it?

My reply is always a counter-question: “What changed?”

After the denials, they finally admit that they installed Visual Studio 2010 SP1 and that resolves the issue. After Visual Studio 2010 SP1 is installed on a workstation with SQL Server 2008 R2 (any release from RTM to CU6), the Intelli-sense feature in the SQL server Management Studio (SSMS) may stop working.

This is a  known, documented issue with Microsoft (KB2531482)and the fix is quite simple – deploy the latest service pack/cumulative update of SQL Server 2008 R2. To know about the latest available build of SQL Server, please refer my post: http://bit.ly/SiOVIw.

Further Reading:

Here are some other posts about Intelli-sense that you may be interested in:

Until we meet next time,

Be courteous. Drive responsibly.

#0236 – SQL Server – SQL OS DMVs – dm_os*


SQL Server Catalog Views & Dynamic Management Views (DMVs) take an administrator to the very heart of SQL Server. DMVs expose vital diagnostic information which are useful to indicate the overall health of the SQL Server. The list of DMVs that changed in SQL Server 2008 R2/2012 is available in one of my previous posts here: http://bit.ly/XobXup.

The SQL Server Operating System (SQLOS) is a layer that lies between the host operating system (Windows OS) and the SQL Server. All interactions of the SQL Server with the underlying operating system are carried out through the SQLOS. SQLOS manages all the operating system services such as memory management, processor and disk interaction, buffer management, hosting external components (e.g. SQL-CLR) etc. Today, we will look at the available SQLOS DMVs and study in detail, the ones introduced in SQL Server 2008 R2/2012.

A full list of documented SQL Server 2012 SQLOS related DMVs is available at: http://msdn.microsoft.com/en-us/library/ms176083.aspx. The DMVs introduced in SQL Server 2008 R2/2012 are:

  • sys.dm_os_cluster_properties
  • sys.dm_os_memory_broker_clerks
  • sys.dm_os_server_diagnostics_log_configurations
  • sys.dm_os_windows_info

sys.dm_os_cluster_properties

Introduced In: SQL Server 2012

Purpose: Returns one record with the current SQL Server resource properties (failover response & logging, detection time, etc). When executed on a stand-alone instance (as my test environment is), no records are returned.

Required Permissions: VIEW SERVER STATE

BOL Link: http://msdn.microsoft.com/en-us/library/gg471591.aspx

sys.dm_os_memory_broker_clerks

Introduced In: SQL Server 2012

Purpose: Memory brokers are internal memory management objects that help the SQL Server regulate the memory allocations across all SQL Server components. Please note that the memory allocations are done by the SQLOS – the memory brokers only document and track memory allocations. Generically speaking, the components that consume memory are called memory clerks. This DMV therefore provides details about the memory allocations of SQL Server’s internal memory consumers.

Required Permissions: VIEW SERVER STATE

BOL Link: N/A – undocumented.

SELECT mbc.clerk_name,
       mbc.total_kb,
       mbc.simulated_kb,
       mbc.simulation_benefit,
       mbc.internal_benefit,
       mbc.external_benefit,
       mbc.value_of_memory,
       mbc.periodic_freed_kb,
       mbc.internal_freed_kb
FROM sys.dm_os_memory_broker_clerks AS mbc;

image

sys.dm_os_server_diagnostics_log_configurations

Introduced In: SQL Server 2012

Purpose: Returns one record for the SQL Server failover cluster diagnostic log. By default, the log is available in the SQL Server default log folder and the DMV also indicates whether diagnostic logging is enabled, number of logs and default size.

Even on a standalone server, one record is returned.

Required permissions: VIEW SERVER STATE

BOL Link: http://msdn.microsoft.com/en-us/library/gg471697.aspx

SELECT dlc.is_enabled,
       dlc.path,
       dlc.max_size,
       dlc.max_files
FROM sys.dm_os_server_diagnostics_log_configurations AS dlc;

image

sys.dm_os_windows_info

Introduced In: SQL Server 2008 R2

Purpose: Returns the service pack/release information of the underlying operating system.

Required Permissions: VIEW SERVER STATE

BOL Link: http://technet.microsoft.com/en-us/library/hh204565.aspx

SELECT wi.windows_release,
       wi.windows_service_pack_level,
       wi.windows_sku,
       wi.os_language_version
FROM sys.dm_os_windows_info AS wi;

Here’s the output from my Windows 8 test system:

image

Until we meet next time,

Be courteous. Drive responsibly.

#0235 – SQL Server – T-SQL Deprecated feature – Start using semi-colons as statement-terminators


A while ago, I read a post from Aaron Bertrand (B|T) regarding an appeal to start using semi-colons actively as statement terminators. Semi-colons as statement-terminators has been around for as long as I can remember, however, they have only been made mandatory in the newer statements:

  • A semi-colon is required before the WITH clause (as in Common Table Expressions, CTE)
  • The MERGE statement must end with a semi-colon
  • In SQL 2012, the THROW statement also requires that the preceding statement ends with a semi-colon

Because the semi-colon is not mandatory, most developers do not use semi-colons in the T-SQL queries that they write. However as Aaron points out, it is already documented in Books On Line that the semi-colon will be a required feature:

Although the semicolon is not required for most statements in this version of SQL Server, it will be required in a future version.

For most teams, this would mean to modify almost every line of code and a huge testing & development effort. To mitigate the high development effort and bring reliability in the process, teams may decide to write a small program that would add semi-colons after each statement. But there’s a small catch.

Exception to the rule: The batch separator cannot be suffixed by a semi-colon.

USE AdventureWorks2012;
GO;

The code above would simply fail to compile with the following error.

Msg 102, Level 15, State 1, Line 2

Incorrect syntax near ‘GO’.

The reason is quite simple – a T-SQL statement is a sub-set of a batch. Because “GO” is a batch separator, it cannot be suffixed by a statement terminator because an active T-SQL batch would not exist at that time.

Reference:

Until we meet next time,

Be courteous. Drive responsibly.