Primarily there are two ways to execute a string or a variable in a string format as sql, they are using EXEC and SP_EXECUTESQL.

 sp_executesql is always to be preferred for executing Dynamic SQL because, sp_executesql supports parameter substitution and also there are more chances of the reuse of execution plan when we use sp_executesql.
 
What we should remember when using sp_ExecuteSQL is that, it always executes as a separate batch irrespective if the batch/ procedure it is contained in.The transact SQL Contained in a variable which is being executed through the SP_ExecuteSQL has its Execution plan generated separately.
 
Here are a set of example on how a sp_Executesql can be used, and what are the basic mistakes that we commit while using sp_Executesql.
 

Using sp_ExecuteSQL, sp_executesql error – Data Type of Vairable

 
Here is a basic example of sp_ExecuteSQL, where we declare a variable and assign a valid sql to it and when executed it throws an error “Procedure expects parameter ‘@statement’ of type ‘ntext/nchar/nvarchar.”
 
This tells us that, it is compulsory to use variable of the above data types.
Use AdventureWorks
GO
DECLARE @SqlStr varchar(500)
SET @SqlStr='SELECT TOP 10 EmployeeID,NationalIDNumber,Title FROM HumanResources.Employee'
EXEC sp_executesql @SqlStr
Msg 214, Level 16, State 2, Procedure sp_executesql, Line 1
Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.

Using sp_ExecuteSQL, sp_executesql error - Parsed and Compiled

 
Now, lets make another mistake deliberately to see what happens if we use an invalid sql statement in the variable which is being executed through sp_ExecuteSQL, it tells us that the sql query in the variable is parsed and compiled only when executed through the sp_ExcuteSQL
Use AdventureWorks
GO
DECLARE @SqlStr nvarchar(500)
SET @SqlStr='SELECT TOP 10 EmployeeID,A_NationalIDNumber,Title FROM HumanResources.Employee'
EXEC sp_executesql @SqlStr
Msg 207, Level 16, State 1, Line 1
Invalid column name 'A_NationalIDNumber'.
 
 

Using sp_ExecuteSQL,Correct Method

 
Now, lets go and put correct sql in the variable and run it using sp_ExecuteSQL to see how it works. 
Use AdventureWorks
GO
DECLARE @SqlStr nvarchar(500)
SET @SqlStr='SELECT TOP 10 EmployeeID,NationalIDNumber,Title FROM HumanResources.Employee'
EXEC sp_executesql @SqlStr

Using sp_ExecuteSQL, Parameter Concatenation

 
The below code snippet shows how a string can be formed dynamically and then be assigned to a variable which is in turn executed through the sp_ExecuteSQL stored procedure
Use AdventureWorks
GO
DECLARE @Employeeid int
DECLARE @SqlStr nvarchar(500)
SET @EmployeeID=10
SET @SqlStr='SELECT TOP 10 EmployeeID,NationalIDNumber,Title FROM HumanResources.Employee WHERE EmployeeID= ' + Cast(@Employeeid as Varchar)
EXEC sp_executesql @SqlStr

Using sp_ExecuteSQL, How to Save the result set in a table

 
This example, shows how a result set that is being returned via sp_ExecuteSQL be stored in a temporary table.
USE AdventureWorks
GO
CREATE TABLE #usp_TestInsertWithSp_exec(EmployeeID int, NationalIDNumber nvarchar(15),Title nvarchar(50))
DECLARE @Employeeid int
DECLARE @SqlStr nvarchar(500)
SET @EmployeeID=10
SET @SqlStr='SELECT TOP 10 EmployeeID,NationalIDNumber,Title FROM HumanResources.Employee WHERE EmployeeID= ' + Cast(@Employeeid as Varchar)
INSERT INTO #usp_TestInsertWithSp_exec
EXEC sp_executesql @SqlStr
SELECT * FROM #usp_TestInsertWithSp_exec
DROP TABLE #usp_TestInsertWithSp_exec

Using sp_ExecuteSQL, OUTPUT Parameters

 
The below code gives a basic example of How to specify output parameters when we use the sp_executesql stored procedure in SQL Server. 
Use AdventureWorks
GO
DECLARE @Employeeid int
DECLARE @NationalID nvarchar(15)
DECLARE @SqlStr nvarchar(500)
SET @EmployeeID=10
SET @SqlStr='SELECT @NationalID= NationalIDNumber FROM HumanResources.Employee WHERE EmployeeID= ' + Cast(@Employeeid as Varchar)+''
EXEC sp_executesql @SqlStr, N'@NationalID nvarchar(15) OUTPUT',@NationalID OUTPUT
PRINT @NationalID
I suppose, that I have covered most of the points on SP_ExecuteSQL, if you have any comments regarding this sp_ExecuteSQL topic or any other topic on SQL Server, Please feel free to comment.
If you have liked the article and want to get the articles (or) new posts at sql like, subscribe to articles through email by entering your email address in the top right and verifying the same.

{ 0 comments }

In the SSAS attribute relationships, what is the difference between Rigid and Flexible Relationships?

In simple terminology, by Rigid the following terms will come into our mind, something which is strict, something which is not so flexible, something which is fixed, firm or stiff and so on. So, even in Analysis Services, it has the same meaning, we use these for dimension attribute which do not change their values over a period of time, for example, if we take Time Dimension, the month May 2010 would always remain under the year 2010 (it’s true, you can believe me on thisJ, and any doubts, check calendar…), the same thing applies to a week in a month or a day in a week, the relationships never change.

So, with the same analogy, flexible is something that has a possibility of change (This is what we have to deal with most of the times, remember the rule, “Change is only constant”), in other terms, there is a possibility of members moving between dimension, taking a standard example for more clarity, let us take Organization -> Employee Department, an employee may be in Sales Department today, he or she can move to Marketing department, or vice versa or what ever other possibility… And another good example would be with respect to customer, customer’s address has a possibility to change, so this relationship between customer name and customer address is definitely going to be a Flexible one!!!

Now, with respect to analysis services, the default value for a relationship type property is flexible, so what does it really mean for us, flexible relationships require Analysis Services to drop and re-compute any existing aggregations during incremental dimension. If we change or define relationship between two attributes to Rigid, the analysis services by default takes the relationship as fixed and does not actually go and re-compute existing relationships and in other words lets the existing relationships remain without clearing them, thereby reducing the incremental process time.

SSAS Attribute Relationships

In the above, the hard lines with dark arrows are the once representing the rigid relationships and the lighter once with transparent arrows are the flexible once.

If looked from other angle, with respect to MDX Query’s on the Cube with say… 30% aggregation, if we fire a MDX and say the numbers we need are not there in the aggregations present, so analysis services in turn has to calculate the numbers that we need from the details, now, it takes in to consideration all the relationships, suppose I need a number @ semester level which is not there in my current aggregations, so if I design a relationship in the time dimension like Year points to semester, semester point to quarter , quarter to month, month to week and week to day. So, here if analysis services calculate the required data for date level, by default it has the required information for returning the data that you need by doing proper summation. So, thus we can say that, the hierarchies with rigid relationships can be queried faster than those with flexible relationships. But, the issue that we would face is, changing any dependent attribute that has a rigid relationship within any hierarchy requires full process of the entire dimension.

Note:this should be present in a checklist for cube development process, because these settings really count for processing as well as query performance.

If you have liked the article and want to get the articles (or) new posts at sql like, subscribe to articles through email by entering your email address in the top right and verifying the same. If you have any comments, then the below form is for you, go ahead!!!

{ 0 comments }

Difference Between UNION and UNION ALL

Developer

What is the difference between union and union all in sql server?
The UNION operator joins result sets from tow or more SELECT statements. The basic Syntax of using “UNION” operator is
SELECT Column List FROM Table1

UNION [ALL]

SELECT Column List FROM Table2

ALL Clause in the query is optional

A couple of things that need to be kept [...]

0 comments Read the full article →

Concatenate Numbers using SQL

Developer

How do we concatenate numbers in sql?
Let us take an example for this, say; we create a table with two integer columns.
USE TempDB

GO

CREATE TABLE concatenate_integers ( col1 int, col2 int)

GO

Now let us put a couple of records over here on which we can run our analysis on.

INSERT INTO concatenate_integers

Values(1,2)

INSERT INTO concatenate_integers

Values(11,12)

INSERT INTO concatenate_integers

Values(21,31)

GO
For concatenation in [...]

0 comments Read the full article →

Types of Keys in Database

General

Super Key
 A combination of one or more columns in a table which can be used to identify a record in a table uniquely, a table can have any number of super keys.
 Candidate Key
 A Column (or) Combination of columns which can help uniquely identify a record in a table without the need of any external data [...]

0 comments Read the full article →

SSAS Allowed Browsing Folders

SSAS

This article is in response to a comment in my previous article “SSAS Database Backup”, the user said that he wants to take the backup of the analysis services database to a custom location and he could not exactly figure it out. When you are in taking the backup of a SSAS Database, and when [...]

0 comments Read the full article →

SSAS Database Backup

SSAS

We need to take regular backup of SSAS database as we do with the SQL Server database to be able to restore it if something severely happens.
When we backup an SSAS Database, it is carried out by analysis services into one single operating system file with an extension of “.abf”, meaning analysis services backup file.
What [...]

2 comments Read the full article →

SQL Select Statement

SQL Basics

Out of all the statements in SQL (Structured Query Language), the Select statement is by far the most used once.
The select statement is used to retrieve data from tables/view/combination of tables and views in a database. The result thus generated using this statement is used for display to users through GUI, for reporting purpose, for [...]

0 comments Read the full article →

SSRS Data Source Losing Credentials

Business Intelligence

This article is based on an issue that I was facing from a couple of days, although did not figure out an exact solution for the same, but the procedure followed and for the learning’s.
In the SQL Server Reporting Services, I was constantly loosing the database credentials for a Shared Data Sources in a Report [...]

0 comments Read the full article →

How to Drop a SQL Server Database

DBA

 Running a DROP statement on an SQL Server is never an easy task as far as the numbers of thoughts that run in our mind at the time of doing that are considered.
So, here is writing up on the process that we need to follow while dropping a SQL Server Database.
Firstly, the decision process that [...]

1 comment Read the full article →