If you are a SQL server DBA at your company, scheduling jobs and automating Admin tasks is a common practice in your daily life. Of course as the number of SQL servers and the underlying databases grow, this vital role for a SQL DBA can quickly get out of hand. This is where SQL Server 2012 Agent can come to your rescue.
SQL Agent is a separate service in SQL server 2012 DBMS. It has the ability to setup and schedule automated jobs that can run on a predefined schedule. This can include DBA things like backing up your databases on a regular intervals, running import and export jobs, executing a predefined Transact SQL scripts and even deploying PowerShell commands.
Let’s go ahead and dig deeper into some of these components
A visual representation of the MS SQL Agent is as follows.
We are going to create a backup job for Northwind database using SQL Agent. First make sure the Agent service is running, if not right click on SQL Server Agent and choose Start. Next do this:
Jobs > New Job
You will get a new dialog box. Enter the following info for job:
Name: Backup Northwind
Category: Database Maintenance
Next go to Steps in the left pane. Then click on New in the middle pane. Basically you are creating a job step that will run the backup command for your database.
For Step name type “Run SQL”
Next go ahead and enter the following SQL code:
BACKUP DATABASE [Northwind] TO DISK = N'C:\SQLBackups\Nwind.bak' WITH NOFORMAT, INIT, NAME = N'Northwind-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10 GO
You always want to parse the sql code and test it. When we ran out SQL command, we got the following output which means that it WORKS!
11 percent processed. 21 percent processed. 31 percent processed. 41 percent processed. 51 percent processed. 61 percent processed. 71 percent processed. 81 percent processed. 91 percent processed. Processed 560 pages for database 'Northwind', file 'Northwind' on file 1. 100 percent processed. Processed 2 pages for database 'Northwind', file 'Northwind_log' on file 1. BACKUP DATABASE successfully processed 562 pages in 0.410 seconds (10.690 MB/sec).
Here is what the new job step looks like in our SQL Server 2012 Agent instance.
Generally you should enable logging which means track execution of your SQL jobs.
Click on Advanced in the left pane
Go ahead Check Log to table and make sure to select Append output to existing entry in table
This basically will provide forensics (big word for SQL geeks) on job executions as time goes on. Btw you can also write this to a file on a shared drive. I actually prefer that option over the Logging table. Click Ok. We can certainly add alerts and a recurring schedule to this. For now lets go ahead and click OK to finally create the sql job in SQL Server 2012 Agent.
Now we are ready for the million dollar question, is this going to work??
Let’s find out by manually executing this job. Under Jobs folder find Backup Northwind. Right click on it and select
Start job at Step
Since we have only one step, the job should start doing its magic. If you did everything correctly, you should get this nice dialog box.
Of course you never assuming anything as a SQL Server DBA and always verify the results. We are going to browse to the folder location and look for the backup file. Here we go:
Yep its there, BINGO!
Other important things SQL Server 2012 Agent can do are the following:
Operators: An operator in SQL server is someone who can be notified or alerted when something goes wrong in SQL server. And it can also be used as FYI information when an important SQL job completes.
Alerts: Alerts are notifications. These are customized SQL alerts based on error messages or Severity levels. Think off an alert as a heads-up which can then in turn execute a job or notify an operator.
Proxies: SQL Server 2012 Agent proxies are specific accounts with particular permission so that you can have fine-tune control on your SQL server. This will minimize any related security risks.
Error logs: This is the placeholder for any execution related info that is tied to a SQL server job or its underlying job steps. Basically this keeps a chronological order of all the executions with different messages that get generated as the job is executing. Def helpful for troubleshooting purposes
At times we need to delete all the user tables in a SQL Server 2012 database. Why do we need to do that? This may happen if:
So this means we have to keep the database intact, just need to drop the tables. There may be other objects like stored procedures, views, user logins and even SQL jobs associated with the database. How do we do that, I mean keep the database but zap all the user tables. Well there are really two options. One is to do it the “old fashioned” way, delete a table one at a time. The other is more elegant and uses TSQL to delete all the user tables in SQL Server 2012. Since we also belong to the Lazy DBA Association, we are going to use TSQL to achieve the end result. We will be doing the following:
Note; Make sure the Referential Integrity is disabled, otherwise this will not work
–declaration of variables
–create temp table #tmp_tables, more info in another script
create table #tmp_tables
(id int identity(1,1),
–insert into temp table #tmp_tables
insert into #tmp_tables (tablename)
SELECT TABLE_SCHEMA + ‘.’ + TABLE_NAME
where TABLE_TYPE=‘base table’
select @total_count=count(*) from #tmp_tables
–while loop to go through the tables
while @rec_count < @total_count
select @table_name= tablename from #tmp_tables where id=@rec_count
select @sql_stmt=‘drop table ‘ + @table_name
set @rec_count=@rec_count + 1
drop table #tmp_tables
/* Sample output
drop table dbo.Employees
drop table dbo.Categories
drop table dbo.Customers
drop table dbo.Shippers
drop table dbo.Suppliers
drop table dbo.Orders
drop table dbo.Products
drop table dbo.Order Details
drop table dbo.CustomerCustomerDemo
drop table dbo.CustomerDemographics
drop table dbo.Region
drop table dbo.Territories
drop table dbo.EmployeeTerritories
drop table dbo.Customers_All
Microsoft SQL 2012 Analysis Services or SSAS has proved to be a major step for Microsoft for the company has been able to project itself as a leader in the field of voluminous data. It promises new, unique and customized solutions for the clients. Microsoft has released a ODBC driver for MS SQL Server that will be capable of running in a Linux environment, allowing the new version to deal with large amounts of data. PowerView with SSRS allows the users to create and consolidate BI reports from all through the Enterprise. The new version is also loaded with distributed relay that allows capturing of workload on the production server and playing the same on a different machine. This allows testing of the schema forming the basis, the support packs and hardware under specific conditions.
SQL Analysis Services are a layer of meta data or a semantic model that resides on the top of a data warehouse in a relational database. This is like an extra layer that stores information about how the fact and the dimension tables in SQL Analysis Services are to be joined and how measures are to be aggregated. It can also be said to be a cache that results in speedy reporting. Before we discuss the Analysis Services features available in SQL Server 2012 in detail let us briefly look at what SQL Server 2012 SP1 has to offer.
It supports Power Pivot MS Excel 2013 and SharePoint and it comes with a brand new architecture based on utilization of Excel utilities for querying, refreshing, loading and saving of the data, which are supported outside the SharePoint 2013 farm. The experience of the user is further enhanced through spPowerpivot.msi which is nothing but an installation package for the windows environment.
This is the result of additional features like the PowerPivot Gallery (SSAS) and the management dashboard. It also incorporates latest Analysis Services in the Tabular mode which includes KPI storage and measures; categorization of data; character extensions and hierarchy annotation. SP1 allows specifying the level of compatibility at the time of creating new Tabular model projects.
SQL Server 2012 SSAS in addition to the earlier features is loaded with new features that help in decision making and data analysis. A prominent feature is introduction of enhanced PowerShell Support and replacement of the Analysis Services Unified Dimensional Model with a hybrid BISM model (BI Sematic Model) permitting BI to be experienced in the SQL 2012 Server environment. The article discusses new features of Analysis Services in detail. For achieving better understanding the new features have been clubbed under various headings.
The new features available with SQL Server 2012 SSAS can be clubbed under seven heads:
Discussing each of the heads and the features that can clubbed under them in detail:
When it comes to new features in Server Instance and Server Monitoring, one of the features is – Availability of 3 analysis services modes. Three server modes Multidimensional and Data Mining which is the default mode, PowerPivot for SharePoint, and Tabular are available for analysis services. The type of solution that is created and deployed depends on the type of server mode. The snapshot illustrated below shows the three deployment modes.
Figure 1: Snapshot illustrating the three deployment modes
In addition to this the xVelocity In-Memory Analytics Engine is available for Tabular Modeling model DBs. Using the in-memory storage it does calculations for collecting the data and manipulating it the moment it is requested.
The next feature that has been added is making available new schema rowsets and a DMV query interface to support the xVelocity engine for data warehousing and latest architecture of SQL Server 2012 PowerPivot service pack 1.
The feature to trace events is yet another important aspect of this version which makes it supportive of the SQL Server Extended Events Framework.
This can be enabled with the help of an XMLA create object script as shown in figure 2 below. For stopping tracing objects, the object has to be deleted using the XMLA delete object script as shown in figure 4 below.
Figure 2: XMLA create object script for enabling SQL 2012 Sever Extended Events Framework.
Figure 3: XMLA delete object script for stopping SQL Sever Extended Events Framework.
The second head of features are clubbed under Analysis Services Tabular Modeling. The features that are available under this head are – Integration of the Tabular Designer Model with SQL Server 2012 Data Tools, availability of administrative support for tabular model databases that can be independently on an Analysis Services server. This version also introduces the SSAS Tabular Model Designer Diagram View which displays inter related tables using a graph and allows filtration of columns, hierarchies and measures. Another feature that can be discussed under this head is partitioning of tables into logically partitioned objects allowing processing of each partition independently. There are some excellent features related to security. While allowing definition of the security roles by defining the permissions of various members included in a tabular model it also allows row level security restricting the access to data.
KPIs can be used for analyzing the performance of a variable by using base and target values. Hierarchies that exist in the form of metadata can be used for determining the relationship between columns. These can be made to appear separately from the rest of the columns. This particular version has no restriction in terms of number rows that a table can contain.
Two important features in this version are – The DirectQuery Mode and the DAX. The DirectQuery Mode that is available in this version provides with an option to deploy in tabular projects. This allows the users and the reporting clients to retrieve the data right from a MS SQL 2012 Server. DAX can be used with both PowerPivot Multidimensional Modeling and Tabular Modeling allowing use of statistical functions, search functions and table functions.
The next head under which features of this SSAS release can be clubbed are multidimensional modeling. The release carries a new option where it is possible to remove a limitation on file storing strings allowing the files to grow as big as they can. In the earlier versions the maximum size of this file could be 4 GB at the most. Any file beyond this size would face an error. It does not mean though that there is no limit on the file now but fortunately it is not regarding the size any more but only limited by the count of strings that could be place in this file.
Other important features available in the release is collection of metrics related to resource usage right at the cmd level while processing a query & is known as Resource Usage Reporting for SSAS Multidimensional Databases.
Two more enhancements over the earlier versions that can be clubbed under this head are – the ability to trace events for the purpose of troubleshooting lock related query or problems related to processing and using DistinctCount in order to help in running the process much faster for the operation gets over to the relations DB engine. Queries can run faster in the DistinctCount process if the criterion that has been laid down is fulfilled. The performance improves as a result of the fact that the operations are offloaded and placed on the relational database engine. The optimization process is not available as a default action. Optimization requires that the following conditions be fulfilled – Presence of one partition for every measure group; absence of random shapes in queries and the relational DB engine should be on SQL Server 2005 or a later version.
SQL Server 2012 SSAS introduces PowerPivot for Excel. Authors can be added and workbooks published using Excel 2010 in SQL Server 2012 and as mentioned above this release also introduces the DAX functions that allows introduction of new statistical functions.
The next two screen shots display more info about SQL PowerPivot
For the release version 2012, a group of features can be clubbed under the heading PowerPivot SharePoint. This version provides an excellent tool for the purpose of installing PowerPivot SharePoint. The first step that the tool undertakes is to perform a scan and determine if PowerPoint configuration is there so that if not, the necessary steps are provided for deployment of operational server. The release also introduces PowerShell Cmdletss for configuration of PowerPivot SharePoint. By using a combination of SharePoint Cmdletss with the newly introduced PowerShell Cmdletss, a PowerPivot SharePoint can be configured. Another feature under this heading is known as a BI Semantic Connection which provides a HTTP endpoint to Analysis Services DBs deployed on a server in the standalone mode. This release provides an improvement in the administration of PowerPivot SharePoint deployment by addition of extra settings. These help detection of problems in advance.
Another feature that is available is the ability to configure automatic upgrade in PowerPivot SharePoint which ensures that the workbooks in SQL 2008 R2 are always up-to-date in tune with the most recent version. This allows data to be refreshed for SQL Server 2012 PowerPivot SharePoint Server workbooks.
Here is the architecture of PowerPivot SharePoint with relation to SQL 2012.
As discussed above the release version 2012 provides DAX functions in both tabular projects and PowerPivot workbooks that are built in the Microsoft SQL Server Data Tools. The release has introduced more than thirty new functions in various categories like statistical, table and search along with security at the level of rows.
Another distinctive and important feature of this version is introduction of PowerShell Cmdlets for AMO enabling navigation, the ability to connect via cmd line, and addition of Analysis Services DBs/databases running on a server in either mode namely Multidimensional Modeling or Tabular Modeling.
This release version also introduces PowerShell Cmdlets for the purpose of configuration of Power Pivot for SharePoint. This can be done by using both SharePoint PowerShell Cmdlets and new ones. A PowerPivot SharePoint installation can be installed through the PowerShell script.
Version 2012 also provides extensions for Automation Management Objects as well as XML for Analysis which are made available in order to provide support for Tabular Modeling and both these types of models use the united BI semantic modeling schema. It helps to utilize different kinds of Application Programming Interfaces. Servers running in either mode can be connected using this feature with the help of Object Linked Database or ADO Multidimensional Modeling.NET.
Last but not least yet another feature which falls in this category of programmability is the CSDL or Conceptual schema definition language which is always useful for representing the tabular model as a response to a query initiated by a client. The nature of the query is such that it can use the schema and the representation for creating visualizations like the Power View. An additional feature to Conceptual schema definition language is the bi: extension which includes various entities, data types and relationships for the tabular models.
In addition to the above, the SQL Server 2012 provides updated provisions SQL Data Tools that can be run in the Visual Studio shell. Tabular and Multidimensional projects are created in the SQL Server 2012 Data Tools and the Visual Studio shell incorporates many IDE enhancements like better readability and maintenance of more than one monitors.
UPDATE statement is one of common DML (data manipulation language) statements. Other DML statements include:
UPDATE query is used to update or modify data in a Table or a View in a database. Using this statement, you can update a single field, multiple fields, single record or multiple records. Need to use WHERE clause to limit affected rows. Without the WHERE clause, you will update all the rows in a table! Ooops! UPDATE query can also use a sub-select aka sub query.
Syntax for UPDATE query
Basic syntax for UPDATE query is:
UPDATE Table or View
SET Column1=value, Column2=value
Common wisdom to use Upper Caps for SQL Keywords
More info here:
For our UPDATE queries today, we will use Northwind (link) database in SQL Server 2012. We will do the following:
Update SQL script is as follows.
You can also download the complete SQL script here:
/*------------------------------------------------------------------------------------------------------------ SQL Tutorial I – SQL UPDATE Statement These example utilizie SQL Server sample database NORTHWIND Also we are using SQL Server 2012 Just fyi: Lines in green starting with -- are comments Words in blue and purple (I guess are SQL Keywords) ------------------------------------------------------------------------------------------------------------*/ --Get the data SELECT * FROM CUSTOMERS SELECT COMPANYNAME, CITY, COUNTRY, REGION FROM CUSTOMERS WHERE COUNTRY='USA' --Update single column, set country to America instead of USA UPDATE Customers SET COUNTRY='AMERICA' WHERE Country='USA' --(13 row(s) affected) SELECT COMPANYNAME, CITY, COUNTRY, REGION FROM CUSTOMERS WHERE COUNTRY='AMERICA' -- 13 ROWS --Multiple columns, country and regions fields --UPDATE CUSTOMERS UPDATE Customers SET COUNTRY='AMERICA', REGION='US' WHERE Country='AMERICA' -- (13 row(s) affected)
Download SQL Video Tutorial here (Right Click – Save As):
or from our YouTube channel:
SQL Server 2012 is package loaded with features and promises to deliver phenomenal results in terms of improvements in performance. Reading or acquiring information about the licensing policy and procedure may be the last thing that a SQL professional would like to do. But for availing the best features of a product and to get maximum benefit from the same it is an important act to be done.
A specific feature and objective of SQL Server 2012 is that it presents information in an altogether intelligent manner to the organization and assists the organization to analyze the data and the information. Some of the features helping SQL 2012 Server deliver the above mentioned objective are AlwaysOn availability, Contained Databases, Uptime enhancement and ColumnStore Index a fast query tool.
While on the other side, the new licensing policy at Microsoft results in increased expenses for the customers. It is also important to bear in mind that to take full benefit of the enhanced features of SQL 2012 means that enhanced network bandwidth is required which is again an additional burden on the Information Technology Department.
SQL Server 2012 is available in 3 versions – Standard, Business Intelligence and Enterprise. The maximum number of new features are available in the SQL 2012 Enterprise Version. Microsoft has also proceeded to replace the licensing model based on per CPU basis to per core.
For the earlier versions of SQL, only one license was required to be bought for every physical processor irrespective of the number of CPU cores in it. Smart choices made at the time of buying server hardware allowed buying up to eight CPU processors for the price of a single SQL Server license. This would allow saving of licensing fee. For procuring the license for SQL Server 2012 for the same server, one would need 8 core licenses. While the new core license fee is reduced than the earlier per CPU fees, but in case someone has an aptitude to do some serious mathematics, it is easy to see the SQL 2012 Server’s prices have increased considerably.
Figure 1: Comparative Features of SQL 2012 Editions
Microsoft released a licensing report for all its customers thinking of associating themselves with this upgraded, brand new technology. Reports by independent agencies like Kirkland brief the SQL 2012 licensing requirements and also offers advice on what issues to take into consideration before buying SQL Server 2012. The important licensing tips are:
Organizations may also like to procure up gradation rights from Windows Server 2008 R2. This is only possible if their license is covered under Software Assurance. As different editions are offered under Windows Server 2008 R2 licensing, up gradation to Windows Server 2012 requires that costs be calculated. To put it in simple words, it would prove less costly in case an organization resorts to licensing Windows Server 2012 for organizations that have “modest virtualization workloads”.
Before proceeding ahead with our discussion, it is important to understand Virtualization Rights.
Microsoft advertises that the Datacenter edition of Windows Server 2012 offers “unlimited” virtualization rights. Even though an organization may have unlimited virtualization rights there is an upper ceiling limit with reference to the number of virtual machines that can run without resulting in any loss of performance. Experts have expressed their an opinion meaning that stacking of licenses (putting two Windows Server 2012 Standard Licenses on one single physical server in order to avail rights to four VMs).
It is also important to determine the number of servers available and how the VMs would be moved around the organization. There are also restrictions on how many times the licenses can be moved between the servers. This is important for volume license cannot be reassigned from one server to another within a period of 90 days.
There is also a possibility that an organization may be required to downgrade from Windows Server 2012 to 2008, in order to run an organization that may not be ready for Windows Server 2012. Down gradation is permitted in case of Datacenter editions.
Another thing that requires the notice of organizations is using the step up license purchases for this is available to Software Assurance customers only. A step up license purchase lets organizations swap a license to a lower edition with a license to a higher edition after paying the price difference.
As part of the SQL 2012 Video Tutorials – Unlimited Package, you will have to access to Transact SQL (TSQL) scripts. These will help you in understanding SQL 2012 and how to work with objects in MS SQL 2012 database environment. Some of the SQL scripts are used to create objects like database, table, indexes, primary keys and foreign key constraints. Other SQL statements include the DML commands like: INSERT, SELECT, UPDATE AND DELETE. Here’s a list of SQL statements so far:
(Note: The ones with active links can be downloaded for FREE!)
More information on this can be found on this page SQL 2012 Video Tutorials – Unlimited Package.
SQL Server Management Studio aka SSMS can be defined as an environment that is integrated for managing the SQL Server Infrastructure. It is a combination of tools that can be used for configuring, monitoring and administering the SQL Server. SQL Server Management Studio also makes available tools for deployment, monitoring and up-gradation of the data tier components like data warehouses and databases that are brought into use by applications and construct queries and corresponding scripts.
There are a number of benefits of SQL Server Management Studio, the most important being that it is a comprehensive utility that manages SQL Server objects. It combines a graphical interface and capabilities related to scripting. It can also be used for managing Database Engine, Analysis Services, Integration Services, and Reporting Services
SQL Server Management Studio supports a number of highly developed features. The general features of the SQL Server are that it is able to support most of the administrative functions and an environment that is integrated and single allows effective authoring and management. There are dialogs that for managing various aspects like objects, Analysis and Reporting Services. Here is a screen capture of what SSMS looks like for SQL Server 2012.
It also supports new Scripting Capabilities. This is supported by the integrated script editors that are contained in the SQL Server Management Studio. The script editors allow authoring Transact-SQL, MDX, DMX, and XML/A. The main features that SQL Server Management Studio supports under this head are a dynamic environment allowing access to information without any loss of time, various ready templates and the ability to customize them, renders support for functions like editing and writing queries and scripts while providing a new interface that allows XML results to be viewed. The Object Explorer part of the SQL Server Management Studio filtration using the entire name, date or schema or a part of it and the asynchronous members are filtered using the metadata. SQL Server Management Studio supports plug-ins and add-ins (extensibility) for it s built upon the Visual Studio Isolated Shell. This allows usage of extensions that have been developed by third parties.
For all stages of development and administration, the SQL Server Management Studio provides a number of powerful tool windows. Some of these tools are capable of being used on any SQL Server part while others are limited to only specific components. The tools that can be used for all the components of SQL server and their purpose are enumerated in the table below:
Can be Viewed
|Object Explorer||This is used for browsing servers, creating and locating objects. It is also used for managing data sources and viewing logs.||This tool can be accessed from the View menu.|
|Solution Explorer||This tool is used for storing and organizing scripts and connection information. SQL Server Scripts can be stored as Solutions and use the source control for managing scripts as their evolvement takes place.||This tool can be accessed from the View menu.|
|Template Explorer||This is used for creating queries that are based on the templates that exist. Custom queries can also be created and alter the templates that are existing.||This tool can be accessed from the View menu.|
|Dynamic Help||This is used for displaying a list of Help topics that are related.||For viewing a particular topic, one needs to click on the name of the specific component.|
The tools in the SQL Server Management Studio work with each other. To explain it with an example, a server can be registered with the Object Explorer and for opening a SQL Editor window that is connected to a specific database.
We provide SQL Server 2012 Tutorial videos including topics on Administration, Development, Programming and Business Intelligence areas. Feel free to check sample training at this page: http://sqlserver2012tutorial.com/free-video-training/
In this blog post on SQL server, we are going to cover Installation of SQL server 2012.
Hardware and software requirements:
We start by going over the hardware and software requirements for SQL 2012 installation. This includes things like:
Additional information is available from web site.
For the purposes of this SQL 2012 install, we are going to use the 3 files option. Once the 3 files are downloaded, you can extract the SQL 2012 Server installation files to a folder. You can get to these files from this location:
Next we run the SETUP.EXE which will launch the SQL Server 2012 Installation center. This is shown right below.
Here we select the Installation option in the left pane and New SQL Server installation in the right pane. Before any software is installed, you need SQL 2012 setup support files. Another way to think about is prerequisite for your SQL server installation.
This is shown in the SQL 2012 Server screenshot below:
Next we are going to choose a set of options including which SQL 2012 server installation, for this one we choose Free edition of SQL Server Evaluation version. On the next screen, we choose SQL Server Feature selection. This includes SQL 2012 features like database engine, SSIS, management tool (SSMS), Integration services, Reporting services, Authentication choices, etc.
Here is what the screenshot looks like for our SQL 2012 install:
We make our SQL Server feature selection and click Next. We highlight SQL Server 2012 “Best Practices” that are used in the industry and then continue the process. This includes items like location of software files, database files, log files and other vital points.
Here is what it looks like on our computer for SQL 2012 Instance Configuration.
For Server Configuration in SQL 2012, it is preferred to use a dedicated domain account. This applies to the database engine service, SQL Server Agent and also other items like SSRS, SSIS and SSAS. For authentication, we use Mixed Mode Authentication. This allows access to SQL Server from Windows and Non-windows environments. Here is a screen capture on the SQL Server installation step.
After all the Installation selections have been made for SQL Server 2012, we get a final summary window. This highlights all the different options you have picked for your SQL Server installation. Please review before you move on to the next screen. We have included a computer monitor picture of this right below:
Go ahead and choose Install. This is when the SQL Server install takes a long time. Why? Because it is copying all the necessary files from installation directory to your computer. If you are falling asleep in the process, this is a good time to get your coffee or tea!!
Here is what it looks like on our end.
At the end of this process, a setup logfile is generated which has all the information regarding the SQL 2012 installation. This should be stored in a secure place. After SQL 2012 installation finishes, you can use the SQL Server Management Studio and verify that the installation process went smoothly. In addition, you can check the MS SQL services using Configuration Manager.
A final confirmation of the SQL 2012 Server installation is as follows:
SQL Server 2012 has quite a few new Transact SQL Commands. We are going to discuss Top 5 of these SQL statements, here are they:
Sequence feature which has been in Oracle for a number of years is now available in MS SQL 2012! A Sequence object is an object that provides functionality similar to Identity (Autonumber) column. The sequence object can be used with more than one table which is not possible in identity object. This is useful when you have parent-child tables and you want to know the value of the ID column before you insert records. We are including some examples here that you can use with SQL Server 2012.
create sequence dbsequence
start with 1 increment by 5
select next value for dbsequence
select next value for dbsequence
drop sequence dbsequence
–With a table
create sequence idsequence
start with 1 increment by 3
create table Products_ext
INSERT dbo.Products_ext (Id, Name)
VALUES (NEXT VALUE FOR dbo.idsequence, ‘ProductItem’)
select * from Products_ext
/* If you run the above statement two types, you will get the following:-
drop table Products_ext
drop sequence idsequence
There are a number of new date functions in Microsoft SQL Server 2012. We are going to discuss two of the following functions:
DATEFROMPARTS function takes three integer parameters and builds a date data type out of them. Here is some SQL 2012 Transact SQL that shows you the DATEFROMPARTS date function in action:
select datefromparts(@year, @month, @day) as mydate
EOMONTH Function: Many applications need the last day of the month for a specific month. EOMONTH Function lets you do just that. Lets check out the following Sql statements:
declare @mydate datetime
Other useful datetime functions in SQL Server 2012 are:
Just like the Data functions, SQL Server 2012 has new features in regards to Logical functions as well. We will take a look at two of them: CHOOSE and IIF SQL functions.
CHOOSE is a simple function and returns the specified index from a list of values. Here are two examples:
Select CHOOSE(2, ‘Kash’, ‘Money’) –Money is second value
Select CHOOSE(1, ‘Kash’, ‘Money’) –Kash is first value
IIF function which is quite popular in MS Office applications is not available in SQL Server 2012. This function takes three arguments. If the first argument is true, it will return the second argument as result or it will return the third argument as result. In other words, it kinda works like a case statement. Here is the TSQL syntax with examples:
–select iif(first argument, second argument, third argument)
select IIF(100>50, ‘true’, ‘false’)
select IIF(100<50, ‘true’, ‘false’)
When you need to combine different text values in SQL Server 2012, you can use the new feature CONCAT. This function helps you concatenate two or strings together. Here is my name with CONCAT function!!
SELECT CONCAT (‘Kash’, ‘Money’, ‘Millionaire’)
–Also can be used in a table, using employees from Northwind database
select * from employees
select concat(firstname, ‘ ‘, lastname) as FullName
Using FORMAT command is especially helpful when you are working with dates in SQL Server 2012. Syntax is as follows:
FORMAT (value, format [,culture])
Lets go ahead and see the Format command in action.
GETDATE(), –native date
FORMAT (GETDATE(), ‘d’), –without leading zero
FORMAT (GETDATE(), ‘dd/MM/yyyy’) –custom format
Output for this is:
2012-08-20 10:36:59.247 8/20/2012 20/08/2012
If you would like to learn more, check out our page on SQL Server 2012 Tutorial.
test 10258 as asf afaf asfas f