September 29, 2012

SQL SERVER: SSMS, Allow to create Stored procedure though table doesn’t exists

We are working on to synchronize our new SQL instance, with existing database and need to make sure all SQL OBJECTS are created on the SQL server instance, so we can execute the same stored procedures from the new SQL instance.

Our assignment is to create same replica of existing database to new SQL instance. We were also pretty much sure because all our Stored Procedures are also created on the new instance. As soon as we try to execute the stored procedure, we are getting, very simple error like:

Invalid object name 'XXXXXX'.

When we debug that, we come to know that TABLES are not created on the new SQL instance because of one error. Our main question here is: How come SQL SERVER allows to create Stored procedures, if table doesn’t exists?

After review it, we come to know that SSMS 2012 has an option, that we can configure this restriction to allow or not to allow, Check for object existence

Check for object existence I SQLYoga Tejas Shah
By default, "Check for object existence” is configures as FALSE, so SQL Server allows user to create stored procedure without checking dependent object is exists or not. Lets see one simple demo:

--Checking, if table exists or not. If it is exists, delete the table
if object_id('SQLYoga') IS NOT NULL
    DROP TABLE SQLYoga

--Creating a Stored procdedure which using the object "SQLYoga" which we have just deleted
CREATE PROC StoredProcedureWithoutObject
As
BEGIN
    SELECT * FROM SQLYoga
END

This is very simple example that first we have checked that, if table called “SQLYoga” exists in the database then drop that table and create a stored procedure which uses this table. As Check for object existence configuration is setup as “to allow”, we are able to create the Stored procedure though table is not exists on the table. Stored procedure won’t be executed and will give an error at the time of execution, as table doesn’t exists. To enable this configuration, go to SSMS->Tools->Options->SQL Server Object Explorer and setup “Check for object existence” to TRUE.

Please let me know your comments

November 21, 2011

SQL SERVER: Develop Reports with RDLC (Asp.Net)

As, I mentioned in my post, Load Reports without SQL SERVER Reporting Service with Asp.Net, we can develop a report without SQL SERVER Reporting Service. That is very simple to do with Microsoft Visual Studio. Please follow the following steps to generate simple report which can be load in browser without SQL SERVER Reporting Service.

We need to follow following steps to generate simple report with RDLC:
1. Create RDLC file.
2. Create Dataset from Report Data Source.
3. Design the Report
4. Runtime pass information to Report Data Source, so report will be generated with Data
Let's create one simple web application with RDLC report.
1. Create RDLC file:
  1. In Solution Explorer, add a new folder and name it as "Reports".
  2. Right click on "Reports", select "Add" and click on" New Items".
  3. Give preferable name to report with extension RDLC and click Add.
image

2. Create Dataset from Report Data Source:
  1. Click on "Report Data" tab displayed on left side of the screen and in case, it is not displayed go to "View" menu and click on "Report Data".
  2. Click on "New" and select "Dataset" as displayed in following screenshot:
image
    3. If your "Data Source" is listed in options, select it from there, else click on "New".
image
     4. If your "Connection" is listed in options, select it from there, else click on "New Connection", to make your connection.

image
    5. Once "Connection" is selected, select your Table/View/Stored Procedure/Function, from which you need to build your report and give appropriate name to Dataset:

image
    6. Once you have selected DB Object in Dataset, you can find out all the columns that are available in selected dataset as follows:
2011-11-18_1506
     7. Once you have this dataset, you will also find that one XSD file is also created in App_code folder, with the same schema, which is used to provide schema definition to RDLC file

RDLC

3. Design the RDLC Report:
                    In Step #2, we have created Dataset with columns that needs to be displayed on the report.  Now its time to use that Dataset and design the report.
You should drag, "Table" from "Toolbox" and assign property "Dataset" created Dataset in Step #2.
  1. RDLC, allows you to design your report with schema that you have selected as DataSet
2011-11-18_1511
4. Runtime pass information to Report Data Source, so report will be generated with Data:
        So far, we have done report designing, now its time to pass actual data to the Report Data Source, so report will be generated with actual Data. To display report on the browser, we have to use "Microsoft Reporting WebForms", which will load the report in the browser with ASPX page. Please follow the steps to pass information to RDLC Report:
  1. Add an "aspx" page in the solution.
  2. We have to use "Report Viewer" control on that page, in which our Report will be displayed
  3. We also need to add few lines of code, to dynamically pass the information (actual data) to the Report Data Source as follows:
using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Web.UI;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Reporting.WebForms;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using System.Data;
using DataAccessLayer;
 
public partial class Reports_ProjectDetail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
          
               string connectionString = ConfigurationManager.ConnectionStrings["PISConnectionString"].ConnectionString;
               Database db = new SqlDatabase(connectionString);
               DbCommand command = db.GetStoredProcCommand("ReportProjectDetail");
        DataSet dataset = db.ExecuteDataSet(command);
               ReportDataSource datasource = new ReportDataSource("DataSet1", Dataset.Tables[0]);
        ReportViewer1.LocalReport.DataSources.Clear();
        ReportViewer1.LocalReport.DataSources.Add(datasource);
        ReportViewer1.LocalReport.Refresh();
        ReportViewer1.Visible = true;      
 }
    }
 
   
}










Let me explain how it works:

1. On Page load, we call one stored procedure to get data from database. Here I have used Microsoft Application block to connect to database and get the information
2. Once, we have the data in DataSet, we have created new "Report Data Source" with the SAME name: "Dataset1" and assign result table as per #1 and assign it to ReportViewer
3. And at last we refresh ReportViewer to display the information as per Datasource provided.

reprotviewf1
This report is ready and you can export it in  Excel, PDF, Word etc. This example is developed in Microsoft Visual Studio 2010

Let me know your comments and difficulties, if any

Reference: Tejas Shah (www.SQLYoga.com)

September 13, 2011

SQL SERVER: Load Reports without SQL SERVER Reporting Service with Asp.Net

Recently, we have weekly meetings with my team and one of developer is come up with question that, "Can we use Reports without having SQL SERVER Report Services?". That is very good question that came up by him, as he says client does not want to have SQL SERVER Reporting Services. Client SQL SERVER is hosted at Shared Hosting and does not want to extra pay to use SQL SERVER Reporting Service.


Answer of his question is, YES. We can have reports without using SQL SERVER Reporting Service with same layout.


Microsoft Visual Studio is providing file called "RDLC" file, by which we can develop report in Microsoft Visual Studio and that Report doesn't need to deploy on Report server and will be called from Asp.Net application itself. By RDLC, it is very simple to load report in browser. We are out of issue to deploy reports on the Report Server and execute it from there. RDLC file remains there with project files.


In the Next post, I will explain in details to configure RDLC report with ASP.Net

June 15, 2011

Community TechDays at Ahmedabad, 2011

 
We had an excellent Community TechDays on 11th June 2011 at Ahmedabad. We have huge crowd to attend the sessions. Please find presentations and demos which speakers have presented during the session.
 
harish

Harish Vaidyanathan [twitter]

Topic: HTML 5
Download Presentation and Demo Files

 
 jacob

Jacob Sebastian [twitter | blog]

Topic: SQL SERVER Worst practices

Download Presentation and Demo Files

 
pinal

Pinalkumar Dave [twitter | blog]

Topic: SQL SERVER Performance troubleshooting using Waits and Queues

 
tejasshah

Tejas Shah [twitter | blog]

Topic: Asp.Net Tips and Tricks

Download Presentation and Demo Files

 

We will upload this session photos soon

 

 

June 4, 2011

Microsoft Community TechDays at Ahmedabad

Great News, Community TechDays event is back on 11th June, 2011 at Ahmedabad. This time I got a chance to have a session in this Community TechDays.

There are attractive sessions as follows:

1. HTML5 - Future of the Web, Harish Vaidyanathan, Evangelist Lead, Microsoft
2. SQL Server Performance Tuning, Pinalkumar Dave, Evangelist, Microsoft
3. T-SQL Worst Practices, Jacob Sebastian, Microsoft MVP
4. LightSwitch On The Cloud!, Mahesh Dhola
5. Asp.Net Tips and Tricks, Me (Tejas Shah)

Please register for the event ASAP.

CTD 201

April 25, 2011

SSRS: Configure User Authentication with ReportCredentials

Many times I found that the Reporting service is configured to access as "Anonymous Access", so any user having URL can access reports from external world. Ideally it should be access by only users/application. For that SQL SERVER Reporting service should not be  accessed by "Anonymous Access". It also prevents Report server from unauthorized access.

NOTE: In shared hosting, Hosting provider provides username/password and only those users can get access to the reports for that specific user.

Today, I am going to explain to how to send user credentials from Report application, so Reporting service can authenticate user and allow to get reports. Only users having correct credentials can access the reports from the server. We are going to configure application to send credentials, so application can get access to the reports.

To configure application to get access reports from Shared hosting/Domain, we need to do following:

1. Get credentials from shared hosting/Domain controller to access the reports

2. Configure Application to Authenticate (.Net)

1. Get credentials:

Whenever we need to deploy/access report from the Report Server, we should have following information:

  • Report Server URL
  • UserName/Password to access the reports

This information will be provided by Shared hosting provider/Domain controller. Information like:

To check this information, Type Report URL in browser. It will ask for Username and password (if anonymous access is disabled). Enter given credentials, if Credentials are correct then Reporting service allow you to access the URL.

2. Configure Application to Authenticate (.Net)

As we get Basic information in step #1, now we need to build application that pass credentials to the Report server, so Report server authenticate the request and allow application to access the reports.

To authenticate request to Report server we need to implement IReportServerCredentials to send Report Credential to Report Server.

  • Create a class to implement IReportServerCredentials

SSRS ReportCredentials (2)

Please find VB code here:

Public Class ReportCredentials
Implements Microsoft.Reporting.WebForms.IReportServerCredentials

Private _userName As String, _password As String, _domain As String

Public Sub New(ByVal userName As String, ByVal password As String, ByVal domain As String)
_userName = userName
_password = password
_domain = domain
End Sub
Public ReadOnly Property ImpersonationUser() As System.Security.Principal.WindowsIdentity _
Implements Microsoft.Reporting.WebForms.IReportServerCredentials.ImpersonationUser
Get
Return Nothing
End Get
End Property

Public ReadOnly Property NetworkCredentials() As System.Net.ICredentials _
Implements Microsoft.Reporting.WebForms.IReportServerCredentials.NetworkCredentials
Get
Return New System.Net.NetworkCredential(_userName, _password, _domain)
End Get
End Property

Public Function GetFormsCredentials(ByRef authCoki As System.Net.Cookie,
ByRef userName As String,
ByRef password As String, _
ByRef authority As String) As Boolean _
Implements Microsoft.Reporting.WebForms.IReportServerCredentials.GetFormsCredentials
userName = _userName
password = _password
authority = _domain
authCoki = New System.Net.Cookie(".ASPXAUTH", ".ASPXAUTH", "/", "Domain")

Return True
End Function

End Class


Now we have created "ReportCredentials" class, now we need to use this class object to send credential info via Report Viewer Control as follows:

SSRS ReportCredentials 2

Please find VB code here:


Imports Microsoft.Reporting.WebForms

Partial Class Report
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load

If Not IsPostBack Then
Dim ReportServerUrl As String = "https:///ReportServer"
Dim ReportDataSourceName As String = "/My Reports/"
With Me.ReportViewer
.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote
With .ServerReport
.ReportServerUrl = New Uri(ReportServerUrl)
.ReportPath = ReportDataSourceName + "ReportName"
.ReportServerCredentials = New _
ReportCredentials("Domain", "UserName", "Password")
.Refresh()
End With
End With
Page.Title = "Reports - " + Request.Params("Report")
If Request.Params("HideOptions") = 1 Then
ReportViewer.ShowParameterPrompts = False
End If
End If
End Sub
End Class

That's it, now you can access your reports deployed at Shared Hosting/Domain from application,
Report server allows to access if credentials are correct.

Let me know if you have any question/problem in deploying/accessing reports from Shared Hosting/Domain.

April 19, 2011

SSRS: Introduction to SQL SERVER Reporting Services

Report is a better presentation of data. From report user/Management can easily analyze the information. Report is easy to explain such information like Sales graph, profitability etc..

SQL SERVER provides rich kind of report that can be easily generated from SQL SERVER and send it to user/management in different formats like Excel, word, HTML etc..SSRS (SQL SERVER Reporting Services) also supports CHARTS which is very useful when we need to develop reports for Management.

To start with report, We can see how to create a report with SSRS. We will learn this by following steps:

1. Create Report.
2. Deploy Report on server
3. Use Report from application (Asp. Net)

1. Create a Report

  • Open Visual Studio and select "Report Server Project"

Introduction to SQL SERVER REPORTING Services SQLYoga#1

  • Check Solution Explorer (Right Side) and click on "Add New Report"

    Introduction to SQL SERVER REPORTING Services SQLYoga#2

  • Select Data Source. Enter information to connect with database and click on "Next"

    Introduction to SQL SERVER REPORTING Services SQLYoga#3

  • Build query which returns data to be displayed on the report.

    Introduction to SQL SERVER REPORTING Services SQLYoga#4

  • Select Report Format. For simple report we select "Tabular" format

    Introduction to SQL SERVER REPORTING Services SQLYoga#5

  • Select which are the columns that needs to be displayed on the report. User can also select columns if report needs to make GROUP BY

    Introduction to SQL SERVER REPORTING Services SQLYoga#6

    For Sample report, I have selected only some of columns that should be displayed on Report.

  • Select Table style

    Introduction to SQL SERVER REPORTING Services SQLYoga

  • Enter Report name, "Sample Report"

    Introduction to SQL SERVER REPORTING Services SQLYoga

    It displays summary info we have selected so far.

    And that's it.

    We are ready with the report now.

    Introduction to SQL SERVER REPORTING Services SQLYoga

    Preview Tab, we can preview report

    Introduction to SQL SERVER REPORTING Services SQLYoga

    So, report is done. Now we need to deploy this report on server, so user can use it from server.

2. Deploy Report to Report Server:

    To deploy report on Report server, we need to have Report server information like Report Server URL, Credentials to connect to Report Server. Today we will just deploy report to Local Report server, I will explain in another post to How to deploy report to the server which requires credentials.

  • Click on Report Project and open Properties:

    Introduction to SQL SERVER REPORTING Services SQLYoga

    Introduction to SQL SERVER REPORTING Services SQLYoga

    Here we need to enter Report server information where we need to deploy this report and from where application/user can get this report.

    • Make OverwriteDataSources : True
    • TargetReportFolder : "My Reports" (given by hosting provider/Remote computer)
    • Target Server URL: <Report URL>(Report Server URL)

    Now we are done with server information and we need to deploy report.

  • Once properties are set, we need to deploy report on server, right click on report file and click on "Deploy"

    Introduction to SQL SERVER REPORTING Services SQLYoga

    Now report is deployed on the server. We can check that report is on server or not by:

    1. Go to your browser (IE, FF, Chrome etc.)

    2. Enter URL: Go to Report Server URL (http://<IP/domain>/ReportServer

    3. It will display page like:

    Introduction to SQL SERVER REPORTING Services SQLYoga

    4. Click on "My Reports"

    Introduction to SQL SERVER REPORTING Services SQLYoga

    Hurray, we can find our reports here on the server.

    Now, report is deployed on the server, now we need to build application from where we need to use this report


3. Use Report from application (Asp.Net)

  • To use this report from Web application, we need to create "New Website" OR you can use existing website if you have.

    Introduction to SQL SERVER REPORTING Services SQLYoga

    Now, in the application, we need to create one ASPX page where we need to use ReportViewer control as follows:

    Introduction to SQL SERVER REPORTING Services SQLYoga

    Microsoft provides this control to load reports in web/desktop application. Now we need to write a code in this page, so Report Viewer control can load report on this page.

    Introduction to SQL SERVER REPORTING Services SQLYoga

     

This is simple code, which tells Report Viewer control to load report. Let me explain each line.

1. ReportServerUrl and ReportDataSourceName are set up with server information.

2. Then we need to setup "ReportName", it tells report viewer control to load that report from Report server.

     .ReportPath = ReportDataSourceName + "ReportName"

    NOTE: "ReportName", will be actual report name

3. And we also need to setup Report Credentials, so "Report server" can allow our application to access this report.

That's it.

Now run application and you can find that you can access "Reports" in application.

August 23, 2010

SQL SERVER: Display Row count of all the tables

Recently we have performance issue in SQL SERVER and we decided to move some large tables to different file group, so we can improve SQL SERVER performance, as it uses other disks I/O. Now challenge is to identify large tables from many tables (approx 700 tables).

There are few ways to display row count of all the tables:
  1. Use Procedure: sp_msForEachTable (Simplest way)

  2. Read information from system tables ( approximate count, Preffered)

Let me explain both of the method:

1. Use Procedure: sp_msForEachTable:

This is the simplest way that we can make COUNT(*) to each table to find number of rows from each table. This is undocumented stored procedure,"sp_msForEachTable" gives ability to make a query to all tables.
EXEC sp_msForEachTable 'SELECT ''?'' AS TableName,COUNT(*) AS NoOfRows FROM ?'

Its nothing but just a simple dynamic SQL statement where "?" will be replaced by table name. So query will be like:
SELECT COUNT(*) FROM BuildVersion


This procedure, "sp_msForEachTable", will loop to each table for current database and count rows from each table. So it gives result like:



By this way, we can get row count from all the tables for current database. But question is: How to use this result set? How to find out which table has maximum rows? To find out this, I need to check each table's rows manually and then only I can find out which table has maximum rows. This is time consuming and not the good way to find out table with maximum rows. Let see another method on which we can find it out it easily.

2. Read information from system tables:

By reading system tables, we can also find out rows from each table. We can use following query to find out number of rows from each table.
SELECT 
 st.Name AS TableName,
 SUM(  
  CASE  
   WHEN (p.index_id < 2) AND (a.type = 1) THEN p.rows  
   ELSE 0  
  END  
 ) AS NoOfRows
FROM sys.partitions p
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
INNER JOIN sys.tables st ON st.object_id = p.Object_ID
INNER JOIN sys.schemas sch ON sch.schema_id = st.schema_id
GROUP BY st.name

NOTE: This method is used to get an *approximate* count for all tables.

This query solved my purpose. In this query, it will give result in single result set, so we can manipulate it easily.



E.g. List out all tables and sort it out based on the NumberOfRows.
So, my query will be:
SELECT 
 st.Name AS TableName,
 SUM(  
  CASE  
   WHEN (p.index_id < 2) AND (a.type = 1) THEN p.rows  
   ELSE 0  
  END  
 ) AS NoOfRows
FROM sys.partitions p
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
INNER JOIN sys.tables st ON st.object_id = p.Object_ID
INNER JOIN sys.schemas sch ON sch.schema_id = st.schema_id
GROUP BY st.name
ORDER BY NoOfRows DESC


Let me know your opinions.

August 8, 2010

SQL SERVER Session at Dotnetchaps - Developer Conference 2010


Dotnetchaps is a group of people focused on Microsoft technologies .Net and SQL Server. The User Group organizes technical sessions for sharing knowledge on .Net and SQL Server. The motto of this group is to Learn, Share and Grow.

DotNetChaps user group is also associated with www.sqlpass.org community and officially opened the SqlPass chapter at Anand. The chapter name is Anand India Sql Server Users group.

Today, I am presenting a SQL SERVER session in this User Group meeting organized at SURAT, GUJARAT.

My session is at 2:10 PM which consists of following:

1. What's new in SQL SERVER 2008 R2?
2. Demo of SSRS Reports

In my SQL SERVER session, I am going to explain Utility Control Point (UCP), Data-Tier Application (DAC), Unicode compression. I am going to explain this feature by making examples on SQL SERVER R2, so people have better idea about it.

For SQL SERVER Reporting Services, its very simple to Design, develop and deploy report to report Server. It is very simple to integrate deployed report to web application.

August 1, 2010

SQL SERVER: Find executing queries

Recently my company owner reported that SQL SERVER is running slow. I searched for it and get following T-SQL query. SQL SERVER provides dynamic views, which contains current information about all details.
 
SELECT OBJECT_NAME(ObjectID) as ObjectName,
  st.Text, 
  DB_NAME(database_ID) as dbname,
  Blocking_session_ID as BlockingSessionID,  
  *
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS st
 
It will give us details like about running SQL Objects, with Database name:
 
 
Reference : Tejas Shah http://www.SQLYoga.com