Total Pageviews

Thursday, June 12, 2014

How to get random dates in a range?

DECLARE @D1 DATE = '20000101'
DECLARE @D2 DATE = '20141231'

   ;WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
        E02(N) AS (SELECT 1 FROM E00 a, E00 b),
        E04(N) AS (SELECT 1 FROM E02 a, E02 b),
        E08(N) AS (SELECT 1 FROM E04 a, E04 b),
        E16(N) AS (SELECT 1 FROM E08 a, E08 b),
        E32(N) AS (SELECT 1 FROM E16 a, E16 b),
   cte(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)
   SELECT TOP 1000
    DATEADD(DAY,ABS(CHECKSUM(NEWID())) % (1+DATEDIFF(DAY,@D1,@D2)),@D1)
   FROM  cte

Thursday, March 27, 2014

How to empty a SQL Server database transaction log file

Sometimes the log file size is more than the db size. In my case, i have 3GB database and 10 GB log files which was occupying all my C drive space and i was not able to run any query against that database. So finally got a script to to truncate the transaction log which saved all my time and effort and the new log file size was 1 MB. Amazing!!

Please use the following script, hopefully you will also need it if you are a DB guy :)

USE DBName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DBName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DBName_log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE DBName
SET RECOVERY FULL;



Tuesday, June 25, 2013

Install Samples Database AdventureWorksDW2012 for SQL Server 2012

AdventureWorks is a Sample Database shipped with SQL Server and it can be downloaded from CodePlex site. AdventureWorks has replaced Northwind and Pubs from the sample database in SQL Server 2005.The Microsoft team keeps updating the sample database as they release new versions.
For SQL Server 2012 RTM Samples AdventureWorks Database is released:

You can download either of the datafile and create database using the same. Here is the script which demonstrates how to create sample database in SQL Server 2012.
 
CREATE DATABASE AdventureWorks2012ON (FILENAME = 'E:\AdventureWorksDW2012_Data.mdf')FOR ATTACH_REBUILD_LOG ;
Please specify your filepath in the filename variable.
 
Note: You might get some error like "you do not have write access", in that case you need to change the properties of AdventureWorksDW2012_Data.mdf file and provide the write access to yourself and then try the steps as mentioned above.
 
Once you have executed the above statement on your SSMS, you will get this message after successful execution.
"
 
 
File activation failure. The physical file name "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2012_log.ldf" may be incorrect.
New log file 'E:\AdventureWorksDW2012_log.ldf' was created.
 
"

Monday, May 13, 2013

Execution Tree in SSIS

Source: http://bidn.com/blogs/KathiKellenberger/sql-server/3097/ssis-transforms-and-execution-trees



The majority of the work performace in most SSIS packages is done in the Data Flow Task. This task allows you to transfer data from a source to a destination with optional transforms in between to clean up and shape the data. While there is a transform for just about anything you can dream up, not all transforms are created equal when it comes to performance.
Some of the transforms, such as the Sort transform, are poor performers, and it is easy to see why. The Sort transform must read all the required data before it can do its work of ordering the data. That is an obvious roadblock.  The Sort transform is called a Blocking Transformation because all incoming records must be read before execution can continue. My colleague, Devin Knight, has a great metaphor for this: a deck of cards. If you are handed 10 cards at a time, you can't have a sorted deck until you have all 52 cards in hand.
Under the covers, SSIS loads data into memory buffers moving chunks of data in and out of the buffers as it peforms the required work. (I’ll explain more about this in a later blog). The blocking transforms create new buffers and execution paths. To be most efficient, you need to minimize the number of new execution paths created. 
While the Sort transform is obviously a poor performer, how can we figure out if the performance of a particular package is suffering because of Blocking Transformations?  There is an event you can log to see how many execution paths are created called “Pipeline Execution Tree.”
To test this, I created a package with a Data Flow Task that added a column to the AdventureWorks Production.Product table, performed an aggregate and a sort before exporting to another database table (Figure 1).
Figure 1: My test package
After testing my package, I enabled logging by right-clicking in the Control Flow area and selecting Logging. I enabled Logging of the Package and Data Flow Task. I added a text file to capture the log and chose the Pipeline Execution Trees event. (See Figures 2 and 3.)
 Figure 2: Configure logging
Figure 3: Log PipelineExecutionTrees
Once I ran the package with the logging in place, I could view the results in Notepad. (Figure 4).
Figure 4: The logging results
These results tell me that there were three execution paths created: 0 to 2. Path 0 starts at the source and contains the Derived Column transform.  That means that the Derived Column transform is a non-blocking transform that works within the existing execution path.  Path 1 begins with the Aggregate output. Path 2 begins with the Sort output. This means that both the Aggregate and Sort transforms created their own buffers and execution  paths and are not among the best performing transforms. Figure 5 shows how the execution paths map to my package.
Figure 5: The execution paths mapped to the package
So, what could I have done to make this particular package perform better? In this case, it is easy to perform all the work of the transforms within our wonderful query language, T-SQL.  I could have eliminated all three transforms by just modifying my query. Of course, sometimes you will need those transforms because the data source doesn’t have the features you need, such as with a flat file. Even then, maybe it would make sense to import a very large flat file into a staging table to take advantage of the database engine.

Difference between Stored Procedures and Functions


  • Procedure can return zero or n values whereas function can return one value which is mandatory.
  • Procedures can have input/output parameters for it whereas functions can have only input parameters.
  • Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
  • Functions can be called from procedure whereas procedures cannot be called from function.
  • Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
  • We can go for transaction management in procedure whereas we can't go in function.
  • Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.
  • UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
  • UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  • Inline UDF's can be though of as views that take parameters and can be used in JOINs and other Rowsetoperations.

Wednesday, March 6, 2013

Creating SSRS report using SSAS cube data source


The creation of an OLAP SSAS report is similar to other SSRS report development once you get to the actual report layout. However, designing your data sources and datasets varies quite a bit from normal relational database data sources and datasets.

The first step in creating a new OLAP based SSRS report is to create a New Project as noted in the below figure. Of course, you could also add a new data source, dataset, and report to an existing project; however in our example, we will utilize a new project with a new report.
New Project
First you will want to create a new Report. We are going to utilize data sources and datasets which reside within the report as opposed to utilizing shared datasets and data sources. To Start the New Report Wizard, Right click on Reports, and select Add New Report.
New Report
The New Report Wizard opens and the first step in the wizard allows for the creation of a data source. You will fill in the New Data Source Name and change the Type to Microsoft SQL Server Analysis Services. Next, select the Connection String Edit button. Fill in your Server Name and then select or type in the appropriate SSAS database name. Be sure to test the connection using the Test Connection.
New Data Source
Depending on the roles created for SSAS Cube you are connecting to, you may have to change the access details noted in the Credentials window. In our demo we will use integrated security, so on the Connection Properties dialog box, click OK. 
After setting up your data source and clicking next, you will now create your dataset to be used in the report. This step requires planning and forethought as to what fields will be displayed on the report and what fields will be used to filter the data both when establishing the dataset and during report generation as parameters. These decisions will impact how the data is returned to the design grid and ultimately to the report itself. In order to define your dataset, click the Query Builder button.
Main Query Screen
The Query Builder button opens the Query Designer Window as displayed in the below figure.
Main Query Screen
The SSAS query designer has several options and methods that will ultimately affect your end report. Initially, you will notice that you have the ability to drag and drop both dimensions and measures onto the results grids. You will additionally notice how the results grid actually flattens your datasets. You can add entire dimensions in one motion by clicking and dragging the Dimension folder onto the results area. Also, the same process works for hierarchies, although you can also add individual attributes from the hierarchy if needed.
Query Builder Complete
There are several buttons in tool bar of the Query Builder that should be noted. For full descriptions of the buttons, please see Analysis Services MDX Query Designer User Interface at http://msdn.microsoft.com/en-us/library/ms403829.aspx. The Show Empty Cells works this same as the MDX Non Empty clause; basically it shows / hides non empty cell values. The Auto Exec button turns on and off the auto execution of queries as you drag and drop dimensions, measures, hierarchies, and attributes onto the results pane. As the results get larger and more complex, it could take longer and longer for the query results to return. The Show Aggregates button again toggles the view of aggregates on and off. Last, the Add Calculated Members button allows for the addition of calculations at the query level. These calculated members could also potentially be added at the report level instead.
Query Builder Button
Furthermore, the query designer contains a filter grid in the upper half of the design area. This filter area serves several purposes:
  1.  Acts as a method to filter the dataset at the query level.
  2. Allows for the easy creation of filters which can also act as parameters. (see additional details about parameters below).
Filters can either be individual attributes or individual parts hierarchies.
Filter Dimensions
The above example filters the dataset at the query level; basically, the query will be restricted to only those items who Calendar Year equals CY 2003. You will also notice that the parameter box is not checked in this first example. Last, since the Auto Exec button is toggled on, the query results will display Calendar Year 2003 data. At this point, we will complete the rest of the wizard setup to create a basic report. Later in our tip, we will discuss the parameter option. Going back to change this option later will also allow us to review making changes to the Data Set after completing the Wizard. Clicking Ok on the Query Builder screen returns you to the Report Wizard with the MDX query now being displayed in the Query String as noted in the next figure. Furthermore, notice that the Calendar Year filter is part of the MDX query text.
QueryString
The report type is selected on the next screen; a matrix report will be used in this demo.
ReportType
We will complete the report by placing Year and Quarter in the Column group, Country in the Row group, and Internet Group Profit and Internet Order Count in the Details area.
Matrix Layout
Next, accept the Matrix Style of Slate.
Matrix Style
Now, finish out the report by completing the Report Name.
ReportFinish
The initial SSAS Report design is now complete. A preview of the design and end report is displayed in the next two figures.
Matrix Style
Of course to completely finish the report you may want to complete some formatting. As such, the numeric fields were immediately formatted to display commas and no decimals.
Report Preview
Our next step is to adjust the dataset filters and replace the hard coded filter for the Calendar Year to a parameter based filter where the report consumers can select which year to display. As noted in the next figure, expand the Datasets folder, and then right click on DataSet1, and select Query to display the Query designer..
Query Step 2
Now, change the Filter Expression to include CY 2002, CY 2003, and CY 2004. Also, check the Parameters check box.
Parameter
Adding these changes now creates a parameter for the Calendar Year which is displayed by expanding the Parameters folder, as shown in the following figure.
Parameter2
Checking the parameter box also adds a hidden dataset, that can be shown by right clicking Datasets and selecting Show Hidden Datasets.
Hidden Data Sets Hidden Data Sets 2
After making this change to add the Calendar Year parameters and previewing the report, as shown in the next figure, you will notice two Alls, Select All and All Periods, appear in the drop down list. The first All is driven by the Report Server MultiParameter option while the second is driven from the MDX query that SSRS runs to populate the Parameters list.
Paramaters 2 Alls
To alleviate this situation, we have several options. Either we can adjust the MDX query or we can add a filter to the dataset to remove the All Member from the results. Using the first option, right click on the Date Calendar Year hidden dataset (after using the technique noted above to show the hidden data set), and then select Query. The first figure below displays the current query. Changing the highlighted word, ALLMEMBERS to CHILDREN adjusts the query to display only the Children of the Calendar Year list and not the All member option.
MDXHidden1
MDX Hidden New Query
Alternately, we can filter the dataset using the filter dataset method; right click on the Date Calendar Year hidden dataset (after using the technique noted above to show the hidden data set), and then select Query Properties. The first figure below displays the current query with its related result set. Within the Dataset Properties Window, clicking on the Filter Option, allows us to filter on any of the fields being returned from the query. In this particular instance, I see that we can easily exclude the All Periods item, by using a filter of ParameterLevel > 0 which is displayed in the second figure below.
Dataset filter Query
Dataset Filter
Now when we run the report, as displayed in the next figure, only the individual years are displayed which provides for a much cleaner option for the report consumers.
Parameter Box




Source: 
http://www.mssqltips.com/sqlservertip/2704/developing-a-ssrs-report-using-a-ssas-data-source/


Sunday, February 24, 2013

Report Deployment on Report Server




Once the report has been made, next we need to deploy that on the report server. To do so, we need to know the report server name.
From the Configuration Tools, we need to choose the Reporting Services Configuration Manager
22.jpg
The Reporting Services Configuration Manager window opens up as shown under
23.jpg
Click on the Connect button and we will be presented with the below screen
24.jpg
I have deliberately highlighted the Reporting Server Database Name (which is ReportServer$NILADRIDENALI). We will see something about it within a short while. Let us click on the Report Manager URL tab in order to get the Report Server URL.
25.jpg
Click on the URL and we will be asked to enter the Windows credentials
26.jpg
Once entered, click on the OK button and we will get a screen as the below
27.jpg
At this point of time let us query the Catalog table of ReportServer$NILADRIDENALI database
 Select * from dbo.Catalog 
and the result is as under
28.jpg
We have done this because when we design a report, Report Definition Language File (rdl) gets generated. It is basically a XML document file that contains all the information about how we design our report. As soon as we deploy the report, the rdl file gets inserted into the Report Server Database. We can query the catalog table to get the information about the same. We will look into that part shortly. But at present, our report is absent in this database.
Now let us come back to our SSRS project. Let us right click on the BasicSSRSReport_Part1 project's properties menu.
29.jpg
Alternatively, we can do the same by choosing the Properties menu from the Projects tab
30.jpg
In either of the case, we will be directed to the properties page where we will enter the Target Server URL obtained from the Report Manager URL of the Reporting Services Configuration Manager.
31.jpg
After we click on the OK button , lets choose the project, right click and click on the Deploy from the available context menu.
32.jpg
If everything goes fine, we will receive a success message
33.jpg
At this point if we query our Catalog table by using the same query as described above, we will receive the below output
34.jpg
So our report has been inserted into the Report Server Database. We can also figure out that, the rdl content has been inserted into the Content column (whose type is image) of the Catalog table. We can obtain the XML content from this hexadecimal representation and then use XQuery to get more information about the reports. To get the XML content, we can issue the below query
Select
 [Report Name] = Name,
 [Rdl Content] = CAST(CAST(Content As Varbinary(Max)) As XML) 
From Catalog
Where Type = 2
The output being as under
35.jpg
Now let us visit our report from the browser. Click the URL available in the Report Manager URL and we will get the below
36.jpg
Now Click on the BasicSSRS_Report_Part1 and it will show the list of available report (in this case only one though i.e. Player Rport).
37.jpg
Click on the Player Report and we will get the Player Report as shown under
38.jpg



This example has been taken from
http://www.codeproject.com/Articles/194097/SSRS-Series-Part-I-Various-ways-of-Report-creation