http://reddymsbitools.blogspot.com

Friday, 22 July 2011

How to Load the pipe delimited flat files into SQL Server ?

Source file:

0|1|2
1|2|3|4|"5|6|7"
1|2|3|4|5
a|b|c|d|"e|f|g"

If we need output below.

column1  ,column2,column3,column4,column5
0,1,2,null,null
1,2,3,4,567
1,2,3,4,5
a,b,c,d,efg

step1:
take the flatfile as a source
step2:
take script component tranformation and add the below code

' Microsoft SQL Server Integration Services user script component
' This is your new script component in Microsoft Visual Basic .NET
' ScriptMain is the entrypoint class for script components

Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

_
_
Public Class ScriptMain
    Inherits UserComponent

    Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
        '
        Dim Column5 As String
        Dim st As Char
        Dim File As String()
        Dim Delimiter As Char
        Delimiter = CChar("|")
        File = Row.Column0.Split(Delimiter)
        If (File.Length > 0) Then
            Row.Col1 = File(0)
        End If
        If (File.Length > 1) Then
            Row.Col2 = File(1)
        End If
        If (File.Length > 2) Then
            Row.Col3 = File(2)
        End If
        If (File.Length > 3) Then
            Row.Col4 = File(3)
        End If
        Dim int As Integer
        int = Row.Column0.IndexOf("""")
        'MsgBox(int)
        If (int < 0) Then
            Column5 = ""
        Else
            Column5 = Row.Column0.Substring(int, Row.Column0.Length - int)
        End If
        Column5 = Column5.Replace("""", "")

        Row.Col5 = Column5.Replace("|", " ")

        ' Add your code here
        '
    End Sub

End Class

step3:
load the data into sql server table

Monday, 28 February 2011

MSBI Interview Questions and Answers

SSIS
1) Use Of Event Handlers
Based on event (On error, on Progress, On Pre/Post Validate..), if you want to perform some action like send email, insert log info into table etc.. we can go for Event Handler Tab.
http://msdn.microsoft.com/en-us/library/ms140011.aspx
http://consultingblogs.emc.com/jamiethomson/archive/2005/06/11/SSIS_3A00_-Custom-Logging-Using-Event-Handlers.aspx
2) Diff b/w script task & script component and its advantages.
Script task is control flow level item where as script component is data flow level item, both of the functionalities are same. This 2 are very powerful items in SSIS.
Normally we can implement custom code by using these components.
By using this two items we can perform any action like DML operations on the data from DB, file and we can do any operation using c# or vb.net code we can use it as Source, destination as well. In single sentence i can conclude the usage of this items we can use to perform any ETL operation if you are good at .net.
http://sqlblog.com/blogs/andy_leonard/archive/2007/10/14/ssis-design-pattern-read-a-dataset-from-variable-in-a-script-task.aspx
http://www.ssistalk.com/2007/04/04/ssis-using-a-script-component-as-a-source/
3) What is a Master package.
Master package is nothing but it is also a normal SSIS package, it act like a master to run the all other (child) packages. If you call the other SSIS packages in a new SSIS package using ‘Execute Package Task’, the new package called as master package. The use of this package(Master) is, instead of running all individual packages if we can run the single master package, then automatically all the child packages will run. Normally we simply schedule the master package in Sql server agent by adding the all child packages values in the master package config file.
http://sqlblog.com/blogs/jorg_klein/archive/2010/01/04/ssis-package-design-pattern-for-loading-a-data-warehouse.aspx
4) Have you worked with data source view in ssis.
You can simply say ‘i never used so far’.
A DSV allows you to create a metadata layer over an existing Data Source. Within a DSV, you can select a subset (or all) of the tables and views available from a Data Source, rename any of the tables/views and/or their columns, add new Named Calculations (which act like computed columns within a table/view), and add new Named Queries (which are complete select statements, which basically act like views).
http://database.blogs.webucator.com/2010/10/20/how-to-create-data-source-views-in-sql-server-integration-services-2008/
5) If there are 100 Packages, do you create 100 configuration files or u create how many.
The answer is based on the requirement we will create 100 config files for 100 packages.If i go for master package and if i am using same kind of connections for the child packages like source and destinations connections then we will create less config files, because Master Package will pass all the connections using master-child relation using the variables. Creation of config files is dependence of the requirement.
http://www.mssqltips.com/tip.asp?tip=1434
http://www.sql-server-performance.com/articles/dba/package_configuration_2005_p1.aspx
ssas
1) Difference b/w Cube-Deploy and Process.
Once you build the cube in the BIDS, we can say the structure of the cube is created. So once the cube structure is built we need to deploy the structure to the actual Sql server analysis server. This process is called DEPLOYMENT of cube. (like creating one object(table) in the relational database)
So once you deploy the structure to the SSAS server, we need to load the data into the structure we have created. This process of loading data into the cube and creating the aggregations is called Cube processing.(like inserting the data into your table)
So to make a cube online for the user for querying we need to build the structure of the cube in BIDS and deploy it to a SSAS server and the process it to load with data and aggregations, then the user can query on the SSAS cube.
Best Practice method to deploy a cube:
http://www.mssqltips.com/tip.asp?tip=1883
2) Different kinds of Dimensions. like Degenerate dimension, Conformed dimension, Junk dimension with example.

Different types of Dimensions:
I.SCD (Slowly Changing Dimension- Type 1 Type 2 and Type 3)
Type 1: The new record replaces the original record. No trace of the old record exists.
Type 2: A new record is added into the customer dimension table. Therefore, the customer is treated essentially as two people.
Type 3: The original record is modified to reflect the change
II. There are other three types of Dimensions:
1. Confirmed Dimensions.
2. Junk Dimensions.
3. Degenerate Dimensions.
-Confirmed Dimension:
The dimensions which is used more than one fact table is called conformed dimensions. It means we can definitely use CD in the nature
Ex: Time,Geography,customer,employee,product etc..
-Junk Dimension:
Junk dimensions are dimensions that contain miscellaneous data (like flags and indicators) that do not fit in the base dimension table.
-Degenerate Dimension :
A degenerate dimension is data that is dimensional in nature but stored in a fact table. For example, if you have a dimension that only has Order Number and Order Line Number, you would have a 1:1 relationship with the Fact table. Do you want to have two tables with a billion rows or one table with a billion rows. Therefore, this would be a degenerate dimension and Order Number and Order Line Number would be stored in the Fact table
III. Cube Dimensions
a. Fact Dimensions
b. Role-Playing Dimensions
c. Reference Dimensions
d. Many-to-Many Dimensions
http://consultingblogs.emc.com/christianwade/archive/2005/04/07/1255.aspx
http://www.informaticans.com/blog/data-warehousing-faqs/dimensions-different-types/

3) About Cube-Partions.its advantage.
We used Partitions to Improve query performance.
A partition is a file on a hard disk that contains a subset of the data included in an Analysis Services database. Partitions let you spread data over multiple hard disks. This includes combinations of both local (stored locally on hard disk) and remote (distributed across multiple hard disks) partitions. Partitions rely on storage settings to define the format and processing schedule for the database, and they use writeback settings to enable what-if analysis. What-if analysis enables a user to input their own data and evaluate the changes that cascade throughout their cube.
Method to create Partitons:
http://www.mssqltips.com/tip.asp?tip=1549

4) What is the use of data source view.
Data Source Views (DSV) have been introduced in SQL Server Analysis Services (SSAS) 2005. A DSV is a metadata layer between the cube and the underlying data source that allows us to build our cubes without being connected to the underlying source
5) iIhave 10 dimensions.i will delete one.and i will process the cube .is that deleted dimension will available in cube?
If you want to remove the dimension from the cube, you can hide/delete the dimension then re-deploy the cube and you need to perform the full process then the deleted dimension won’t appear in the cube.
6) diff b/w calculated members and calculated measures
Member is nothing but column on dimension table. Measure is nothing but column on fact table.
The term calculated member refers to the creation of any MDX object through a calculation. The calculated member can be part of the measures dimension where a simple MDX expression such as addition or subtraction of two or more base measures results in a new measure. Such calculated members on the measure dimension are referred to as calculated measures.
Calculated Member is related to the Dimension where as calculated Measure is related to the measure in measure group.
http://msdn.microsoft.com/en-us/library/ms166568.aspx
SSRS
1) types of parameters
Single value parameters, Multi value parameters,
Cascading parameters (one parameter is dependent on another parameter selection)
http://msdn.microsoft.com/en-us/library/aa337234.aspx
http://sql-bi-dev.blogspot.com/2010/07/report-parameters-in-ssrs-2008.html

2) what are drill through and drill down reports.
Drill down is when a power play model has several levels within a hierarchy. Given a location dimension with country/ state and city. A starting view will show the summary of countries, Drill down on one country will expose their states, drill down on a state will show their cities. So drill down goes to lower levels of a dimension as designed in the model.
Drill thru is the ability to leave PowerPlay and call a SQL Query, (say in Impromptu) passing the dimension line as filters to the query. If the columns in the query match the columns used to build the dimensions the query will automatically apply those values to the where clause. You can write any query or queries you want to support a drill thru from a cube. Context is important to balance the two
Database
1) How u done partitions.
If your database contains very large tables, you may benefit from partitioning those tables onto separate filegroups. This technology, introduced in SQL Server 2005, allows you to spread data onto different physical disks, leveraging the concurrent performance of those disks to optimize query performance.
http://www.mssqltips.com/tip.asp?tip=1914

2) Difference b/w view and materliazed view.
Views
A view takes the output of a query and makes it appear like a virtual table. You can use a view in most places where a table can be used.
All operations performed on a view will affect data in the base table and so are subject to the integrity constraints and triggers of the base table.
A View can be used to simplify SQL statements for the user or to isolate an application from any future change to the base table definition. A View can also be used to improve security by restricting access to a predetermined set of rows or columns.
In addition to operating on base tables, one View can be based on another, a view can also JOIN a view with a table (GROUP BY or UNION).

Materialized Views
Materialized views are schema objects that can be used to summarize, precompute, replicate, and distribute data. E.g. to construct a data warehouse.
A materialized view provides indirect access to table data by storing the results of a query in a separate schema object. Unlike an ordinary view, which does not take up any storage space or contain any data.

The existence of a materialized view is transparent to SQL, but when used for query rewrites will improve the performance of SQL execution. An updatable materialized view lets you insert, update, and delete
3) Have u worked with sequences.
CREATE SEQUENCE will enter a new sequence number generator into the current database. This involves creating and initializing a new single-row table with the name seqname. The generator will be owned by the user issuing the command.
http://blogs.msdn.com/b/sqlcat/archive/2006/04/10/sql-server-sequence-number.aspx

4) About logging in view.
http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_6003.htm

Frequently asked Sql Queries with answers
http://blog.sqlauthority.com/2007/04/21/sql-server-interview-questions-and-answers-complete-list-download/
http://www.java2s.com/Code/SQLServer/CatalogSQLServer.htm

Some Other Interview Questions:
http://www.bigresource.com/MS_SQL-ssis-master-package-fail--MaixRNiy.html
Try to get the info from net.I do not have time to explain all these...
DTS vs SSIS: A basic overview
http://decipherinfosys.wordpress.com/2008/03/11/dts-vs-ssis-a-basic-overview/
How to create a basic Cube
http://www.mssqltips.com/tip.asp?tip=1532

MSBI - Some IMP URL

***->MSBI-Books to read****

SSIS-ETL World Record

Today at the launch of SQL Server 2008, you may have seen the references to world-record performance doing a load of data using SSIS. Microsoft and Unisys announced a record for loading data into a relational database using an Extract, Transform and Load (ETL) tool. Over 1 TB of TPC-H data was loaded in under 30 minutes. I wanted to provide some background material in the form of a Q&A on the record, since it’s hard to give many details in the context of a launch event. We are also planning a paper that talks about all this, so think of this article as a place-holder until the full paper comes along. I hope you find this background information useful.
-- See the below link for more info
http://blogs.msdn.com/sqlperf/archive/2008/02/27/etl-world-record.aspx

SSAS-Storage Modes in Analysis Services

Why did we only use the MOLAP storage mode in Project REAL? There is also ROLAP and HOLAP storage, but they weren’t used at all. Also, why doesn’tProject REAL illustrate pro-active caching?

The Analysis Services 2005 Performance Guide contains a more complete discussion of the storage modes in Analysis Services in Appendix B. Because the question comes up from time to time regarding Project REAL, this write-up gives a summary.

Every partition in AS has an associated storage mode. MOLAP partitions store aggregations and a copy of the source data (fact and dimension data) in a multidimensional structure on the Analysis server. This is the optimal storage mode for several reasons:
Compression. When relational data is processed into AS, the storage needed is typically 20% to 40% of the size of the un-indexed relational fact table. Less I/O means that the MOLAP data is faster to access.
Multidimensional structure. The format in which AS data is stored is optimized for the kind of access that OLAP users do – access to the data using arbitrary dimensions and arbitrary slices of the dimension.
Data local to AS. There is no need for AS to call out to another service to obtain data when MOLAP storage is used.
Indexes are not needed on relational fact tables. When AS processes fact data, it generally can do a full table scan, so indexes are not needed. When there are multiple partitions in a measure group, there will be one join to the dimension that is used for partitioning, but that’s all. Then at query time, no requests are sent to the relational database, so no indexes are needed for querying. Given that indexes can multiply the size of data in the relational system, the space savings can be significant.

HOLAP partitions store aggregations in a multidimensional structure on the Analysis server, but do not copy fact data from the original relational database. As a result, whenever Analysis Services needs to resolve a query against fact data stored in a HOLAP partition, Analysis Services must query the relational database rather than using a multidimensional structure stored on the Analysis server. Some administrators choose HOLAP because HOLAP appears to require less total storage space while yielding high performance queries. However, the disadvantages almost always outweigh the advantages:
When a query “misses” the aggregations AS will have to query the relational database for fact-level data. This is necessarily slower than getting data from the compressed and natively multidimensional MOLAP storage.
Because of the above, many administrators will create more aggregations to decrease the number of “misses.” At some point the additional aggregations can become larger than the fact data would have been. But even if it doesn’t, more aggregations take more time to process.
Processing of HOLAP partitions is not significantly faster than processing of MOLAP partitions. In both cases the entire fact table must be read into AS in order to create aggregations. The only difference is whether AS also saves the fact data. However if more aggregations were created because of the previous point, processing will be slower.

ROLAP partitions store aggregations in the same relational database that stores the fact data. ROLAP partitions take longer to process, and because all queries must be redirected to the relational database, ROLAP partitions are slower to query against as well.

Given all this, it sounds like only MOLAP should ever be used! For most implementations that is the case. The exception is when near-real-time access is needed to data that changes throughout the day. Even there, pro-active caching is the first technique of choice. However, if even pro-active caching does not allow frequent enough updates, then the use of one ROLAP partition in the measure group is a way to handle the incoming data.

The recommended way to handle near-real-time scenarios is to take advantage of the fact that the storage mode is set on a per-partition basis. A vast majority of data in an OLAP cube does not change throughout the day. That data should be stored in MOLAP partitions. One partition in the measure group is designated to receive updates as they come in. That way, only that partition needs to be updated. This partition can be updated using proactive caching or it can be defined as a ROLAP partition with zero aggregations. In the latter case, all queries to this partition will be sent to the relational source, and current data will always be as current as that table.

For more details about near-real-time data access, see the section “Near Real-Time Data Refreshes” in the Analysis Services 2005 Performance Guide.

An example of how such a partitioning scheme would be updated might look like this:
Fact tables contain weekly partitions in the RDBMS, and there are corresponding weekly partitions in AS.
Each night, data for the previous day is processed into the correct weekly partition.
As new data comes in during the day, it flows into a relational partition for current updates. AS has a near-real-time partition that maps to that relational partition. Either using pro-active caching or a ROLAP partition with zero aggs, users get access to new data throughout the day.
At night, the collected daily data is moved to the weekly partition and processed (either by full process or using incremental update). The near-real-time partition is now ready to collect the next day’s updates.

Returning to the original question: Why did we only use the MOLAP storage mode in Project REAL? The simple answer is that MOLAP storage performs the best. The slightly extended answer is that Project REAL is based on the scenario in the Barnes & Noble data warehouse. The business model centered on daily updates, not near-real-time access. Therefore, there was no need for proactive caching or ROLAP partitions

SSRS-Scale-Out Deployment Best Practices

Check out the the third of five technical note as part of the Building and Deploying Large Scale SQL Server Reporting Services Environments Technical Note Series: Reporting Services Scale-Out Deployment Best Practices
This technical note reviews the
SSRS Scale-Out Architecture
Report Catalog sizing
The benefits of File System snapshots for SSRS 2005
Why File System snapshots may not help for SSRS 2008
Using Cache Execution
Load Balancing your Network
Isolate your workloads
Report Data Performance Considerations

SSIS - Full-load vs. Delta-Load

SSRS - Adding Subreports

A subreport is a report item that displays another report inside the body of a main report. Conceptually, a subreport is similar to a frame in a Web page. It is used to embed a report within a report. Any report can be used as a subreport. The report that the subreport displays is stored on a report server, usually in the same folder as the parent report. You can design the parent report to pass parameters to the subreport. A subreport can be repeated within data regions, using a parameter to filter data in each instance of the subreport.
If you use subreports to display separate groups of data, consider using data regions (tables, matrices, lists, charts, or gauges) instead. Reports with data regions only may perform better than reports that include subreports.
Use data regions when you need to nest groups of data from the same data source within a single data region. Use subreports if you need to nest groups of data from different data sources within a single data region, reuse a subreport in multiple parent reports, or display a standalone report inside of another report. You can create a "briefing book" by placing multiple subreports inside the body of another report.
Note:
In Report Designer, if you preview a report that contains subreports, and then change the subreport, the preview may not be updated. To see the changes, click the Refresh button.
Using Parameters in Subreports
To pass parameters from the parent report to the subreport, define a report parameter in the report that you use as the subreport. When you place the subreport in the parent report, you can select the report parameter and a value to pass from the parent report to the report parameter in the subreport.
Note:
The parameter that you select from the subreport is a report parameter, not a query parameter. For more information about parameters, see Adding Parameters to Your Report.
You can place a subreport in the main body of the report, or in a data region. If you place a subreport in a data region, the subreport will repeat with each instance of the group or row in the data region. To pass a value from the group or row to the subreport, in the subreport value property, use a field expression for the field containing the value you want to pass to the subreport parameter.
For more information about working with subreports, see How to: Add a Subreport and Parameters (Reporting Services).

For More Details:-
Here is the good link aboutSubReport
http://www.simple-talk.com/content/print.aspx?article=278

SSIS-Waiting for a file

SSIS - Difference between Control Flow and Data Flow

SSIS-Parallel Execution

Hi,
this is important one to achieve parallel execution using SSIS.

http://shujaatsiddiqi.blogspot.com/2008/10/ssis-multithreading-parallel-execution.html

SSIS-Performance Tuning Techniques(SSIS Engine Overview,BlockingExecution Trees, Buffer Sizing, Parallelism)

Hi Performance tuning is very important one as a process of data loading using ETL tools.
When you architect data integration solutions, your design decisions not only determine how successfully your solution meets functional requirements, but also how well your solution meets performance requirements. To make the right performance design decisions, you need to understand the performance architecture of your data integration tool and, just as importantly, the techniques that enable you to maximize the tool’s utilization of system resources such as memory and CPU.
Microsoft® SQL Server™ 2005 Integration Services (SSIS) provides full-featured data integration and workflow engines coupled with a rich development environment for building high-performance data integration solutions. SSIS provides a variety of optimization opportunities to help you maximize resource utilization while successfully meeting the needs of your specific data integration scenario.
http://msdn.microsoft.com/en-us/library/cc966529.aspx

http://shujaatsiddiqi.blogspot.com/2008/08/performance-improvement-of-sql-server.html

SQL SERVER – Nth Highest Salary

SSIS-Transactions usage

Saturday, 26 February 2011

generate insert script for database tables

CREATE PROC [sp_generate_inserts]
(
@table_name varchar(776), -- The table/view for which the INSERT statements will be generated using the existing data
@target_table varchar(776) = NULL, -- Use this parameter to specify a different table name into which the data will be inserted
@include_column_list bit = 1, -- Use this parameter to include/ommit column list in the generated INSERT statement
@from varchar(800) = NULL, -- Use this parameter to filter the rows based on a filter condition (using WHERE)
@include_timestamp bit = 0, -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the INSERT statement
@debug_mode bit = 0, -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
@owner varchar(64) = NULL, -- Use this parameter if you are not the owner of the table
@ommit_images bit = 0, -- Use this parameter to generate INSERT statements by omitting the 'image' columns
@ommit_identity bit = 0, -- Use this parameter to ommit the identity columns
@top int = NULL, -- Use this parameter to generate INSERT statements only for the TOP n rows
@cols_to_include varchar(8000) = NULL, -- List of columns to be included in the INSERT statement
@cols_to_exclude varchar(8000) = NULL, -- List of columns to be excluded from the INSERT statement
@disable_constraints bit = 0, -- When 1, disables foreign key constraints and enables them after the INSERT statements
@ommit_computed_cols bit = 0 -- When 1, computed columns will not be included in the INSERT statement

)
AS
BEGIN

/***********************************************************************************************************
Procedure: sp_generate_inserts (Build 22)

Purpose: To generate INSERT statements from existing data.
These INSERTS can be executed to regenerate the data at some other location.
This procedure is also useful to ALTER a database setup, where in you can
script your data along with your table definitions.

Tested on: SQL Server 7.0 and SQL Server 2000

NOTE: This procedure may not work with tables with too many columns.
Results can be unpredictable with huge text columns or SQL Server 2000's sql_variant data types
Whenever possible, Use @include_column_list parameter to ommit column list in the INSERT statement, for better results
IMPORTANT: This procedure is not tested with internation data (Extended characters or Unicode). If needed
you might want to convert the datatypes of character variables in this procedure to their respective unicode counterparts
like nchar and nvarchar


Example 1: To generate INSERT statements for table 'titles':

EXEC sp_generate_inserts 'titles'

Example 2: To ommit the column list in the INSERT statement: (Column list is included by default)
IMPORTANT: If you have too many columns, you are advised to ommit column list, as shown below,
to avoid erroneous results

EXEC sp_generate_inserts 'titles', @include_column_list = 0

Example 3: To generate INSERT statements for 'titlesCopy' table from 'titles' table:

EXEC sp_generate_inserts 'titles', 'titlesCopy'

Example 4: To generate INSERT statements for 'titles' table for only those titles
which contain the word 'Computer' in them:
NOTE: Do not complicate the FROM or WHERE clause here. It's assumed that you are good with T-SQL if you are using this parameter

EXEC sp_generate_inserts 'titles', @from = "from titles where title like '%Computer%'"

Example 5: To specify that you want to include TIMESTAMP column's data as well in the INSERT statement:
(By default TIMESTAMP column's data is not scripted)

EXEC sp_generate_inserts 'titles', @include_timestamp = 1

Example 6: To print the debug information:

EXEC sp_generate_inserts 'titles', @debug_mode = 1

Example 7: If you are not the owner of the table, use @owner parameter to specify the owner name
To use this option, you must have SELECT permissions on that table

EXEC sp_generate_inserts Nickstable, @owner = 'Nick'

Example 8: To generate INSERT statements for the rest of the columns excluding images
When using this otion, DO NOT set @include_column_list parameter to 0.

EXEC sp_generate_inserts imgtable, @ommit_images = 1

Example 9: To generate INSERT statements excluding (ommiting) IDENTITY columns:
(By default IDENTITY columns are included in the INSERT statement)

EXEC sp_generate_inserts mytable, @ommit_identity = 1

Example 10: To generate INSERT statements for the TOP 10 rows in the table:

EXEC sp_generate_inserts mytable, @top = 10

Example 11: To generate INSERT statements with only those columns you want:

EXEC sp_generate_inserts titles, @cols_to_include = "'title','title_id','au_id'"

Example 12: To generate INSERT statements by omitting certain columns:

EXEC sp_generate_inserts titles, @cols_to_exclude = "'title','title_id','au_id'"

Example 13: To avoid checking the foreign key constraints while loading data with INSERT statements:

EXEC sp_generate_inserts titles, @disable_constraints = 1

Example 14: To exclude computed columns from the INSERT statement:
EXEC sp_generate_inserts MyTable, @ommit_computed_cols = 1
***********************************************************************************************************/

SET NOCOUNT ON

--Making sure user only uses either @cols_to_include or @cols_to_exclude
IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
BEGIN
RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
END

--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
BEGIN
RAISERROR('Invalid use of @cols_to_include property',16,1)
PRINT 'Specify column names surrounded by single quotes and separated by commas'
PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_include = "''title_id'',''title''"'
RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
END

IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
BEGIN
RAISERROR('Invalid use of @cols_to_exclude property',16,1)
PRINT 'Specify column names surrounded by single quotes and separated by commas'
PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_exclude = "''title_id'',''title''"'
RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
END


--Checking to see if the database name is specified along wih the table name
--Your database context should be local to the table for which you want to generate INSERT statements
--specifying the database name is not allowed
IF (PARSENAME(@table_name,3)) IS NOT NULL
BEGIN
RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
END

--Checking for the existence of 'user table' or 'view'
--This procedure is not written to work on system tables
--To script the data in system tables, just ALTER a view on the system tables and script the view instead

IF @owner IS NULL
BEGIN
IF ((OBJECT_ID(@table_name,'U') IS NULL) AND (OBJECT_ID(@table_name,'V') IS NULL))
BEGIN
RAISERROR('User table or view not found.',16,1)
PRINT 'You may see this error, if you are not the owner of this table or view. In that case use @owner parameter to specify the owner name.'
PRINT 'Make sure you have SELECT permission on that table or view.'
RETURN -1 --Failure. Reason: There is no user table or view with this name
END
END
ELSE
BEGIN
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @owner)
BEGIN
RAISERROR('User table or view not found.',16,1)
PRINT 'You may see this error, if you are not the owner of this table. In that case use @owner parameter to specify the owner name.'
PRINT 'Make sure you have SELECT permission on that table or view.'
RETURN -1 --Failure. Reason: There is no user table or view with this name
END
END

--Variable declarations
DECLARE @Column_ID int,
@Column_List varchar(8000),
@Column_Name varchar(128),
@Start_Insert varchar(786),
@Data_Type varchar(128),
@Actual_Values varchar(8000), --This is the string that will be finally executed to generate INSERT statements
@IDN varchar(128) --Will contain the IDENTITY column's name in the table

--Variable Initialization
SET @IDN = ''
SET @Column_ID = 0
SET @Column_Name = ''
SET @Column_List = ''
SET @Actual_Values = ''

IF @owner IS NULL
BEGIN
SET @Start_Insert = 'INSERT INTO ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'
END
ELSE
BEGIN
SET @Start_Insert = 'INSERT ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'
END


--To get the first column's ID

SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



--Loop through all the columns of the table, to get the column names and their data types
WHILE @Column_ID IS NOT NULL
BEGIN
SELECT @Column_Name = QUOTENAME(COLUMN_NAME),
@Data_Type = DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE ORDINAL_POSITION = @Column_ID AND
TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



IF @cols_to_include IS NOT NULL --Selecting only user specified columns
BEGIN
IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0
BEGIN
GOTO SKIP_LOOP
END
END

IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
BEGIN
IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0
BEGIN
GOTO SKIP_LOOP
END
END

--Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1
BEGIN
IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
SET @IDN = @Column_Name
ELSE
GOTO SKIP_LOOP
END

--Making sure whether to output computed columns or not
IF @ommit_computed_cols = 1
BEGIN
IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1
BEGIN
GOTO SKIP_LOOP
END
END

--Tables with columns of IMAGE data type are not supported for obvious reasons
IF(@Data_Type in ('image'))
BEGIN
IF (@ommit_images = 0)
BEGIN
RAISERROR('Tables with image columns are not supported.',16,1)
PRINT 'Use @ommit_images = 1 parameter to generate INSERTs for the rest of the columns.'
PRINT 'DO NOT ommit Column List in the INSERT statements. If you ommit column list using @include_column_list=0, the generated INSERTs will fail.'
RETURN -1 --Failure. Reason: There is a column with image data type
END
ELSE
BEGIN
GOTO SKIP_LOOP
END
END

--Determining the data type of the column and depending on the data type, the VALUES part of
--the INSERT statement is generated. Care is taken to handle columns with NULL values. Also
--making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
SET @Actual_Values = @Actual_Values +
CASE
WHEN @Data_Type IN ('char','varchar','nchar','nvarchar')
THEN
'COALESCE('''''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('datetime','smalldatetime')
THEN
'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',109))+'''''''',''NULL'')'
WHEN @Data_Type IN ('uniqueidentifier')
THEN
'COALESCE('''''''' + REPLACE(CONVERT(char(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('text','ntext')
THEN
'COALESCE('''''''' + REPLACE(CONVERT(char(8000),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('binary','varbinary')
THEN
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'
WHEN @Data_Type IN ('timestamp','rowversion')
THEN
CASE
WHEN @include_timestamp = 0
THEN
'''DEFAULT'''
ELSE
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'
END
WHEN @Data_Type IN ('float','real','money','smallmoney')
THEN
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ',2)' + ')),''NULL'')'
ELSE
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ')' + ')),''NULL'')'
END + '+' + ''',''' + ' + '

--Generating the column list for the INSERT statement
SET @Column_List = @Column_List + @Column_Name + ','

SKIP_LOOP: --The label used in GOTO

SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND
ORDINAL_POSITION > @Column_ID AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)


--Loop ends here!
END

--To get rid of the extra characters that got concatenated during the last run through the loop
SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)

IF LTRIM(@Column_List) = ''
BEGIN
RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter
END

--Forming the final string that will be executed, to output the INSERT statements
IF (@include_column_list <> 0)
BEGIN
SET @Actual_Values =
'SELECT ' +
CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + '''' + RTRIM(@Start_Insert) + ' ''+' + '''(' + RTRIM(@Column_List) + '''+' + ''')''' + ' +''VALUES(''+ ' + @Actual_Values + '+'')''' + ' ' + COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)') END ELSE IF (@include_column_list = 0) BEGIN SET @Actual_Values = 'SELECT ' + CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + '''' + RTRIM(@Start_Insert) + ' '' +''VALUES(''+ ' + @Actual_Values + '+'')''' + ' ' + COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)') END --Determining whether to ouput any debug information IF @debug_mode =1 BEGIN PRINT '/*****START OF DEBUG INFORMATION*****' PRINT 'Beginning of the INSERT statement:' PRINT @Start_Insert PRINT '' PRINT 'The column list:' PRINT @Column_List PRINT '' PRINT 'The SELECT statement executed to generate the INSERTs' PRINT @Actual_Values PRINT '' PRINT '*****END OF DEBUG INFORMATION*****/' PRINT '' END PRINT '--INSERTs generated by ''sp_generate_inserts'' ' PRINT 'SET NOCOUNT ON' PRINT '' --Determining whether to print IDENTITY_INSERT or not IF (@IDN <> '')
BEGIN
PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' ON'
PRINT 'GO'
PRINT ''
END


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
BEGIN
IF @owner IS NULL
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
END
ELSE
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
END

PRINT 'GO'
END

PRINT ''
PRINT 'PRINT ''Inserting values into ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ''''


--All the hard work pays off here!!! You'll get your INSERT statements, when the next line executes!
EXEC (@Actual_Values)

PRINT 'PRINT ''Done'''
PRINT ''


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
BEGIN
IF @owner IS NULL
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
END
ELSE
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
END

PRINT 'GO'
END

PRINT ''
IF (@IDN <> '')
BEGIN
PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' OFF'
PRINT 'GO'
END

PRINT 'SET NOCOUNT OFF'


SET NOCOUNT OFF
RETURN 0 --Success. We are done!
END

Rollup And Cube

CREATE TABLE ORDERS (CUSTOMERNAME VARCHAR(50),ITEMNAME VARCHAR(50),PRICE NUMERIC(10,2))

INSERT INTO ORDERS VALUES('JACOB','ITEM1',312.50 )
INSERT INTO ORDERS VALUES('JACOB','ITEM2', 480.00 )
INSERT INTO ORDERS VALUES('MIKE','ITEM1',75.00 )
INSERT INTO ORDERS VALUES('MIKE','ITEM2',44.00 )
----ROLLUP
SELECT
CASE
WHEN GROUPING(customername) = 1 THEN 'All Customer'
ELSE customername END CustomerName,
CASE WHEN GROUPING(itemname) = 1 THEN 'All Items'
ELSE itemname END ItemName,
SUM(Price)
FROM orders GROUP BY customername,itemname
WITH ROLLUP

---CUBE
SELECT
CASE
WHEN GROUPING(customername) = 1 THEN 'All Customer'
ELSE customername END CustomerName,
CASE WHEN GROUPING(itemname) = 1 THEN 'All Items'
ELSE itemname END ItemName,
SUM(Price)
FROM orders GROUP BY customername,itemname
WITH CUBE

Triggers Concepts

select * from customer_test

--------------------

create table customer_test (id int identity primary key,

name varchar(100),dept varchar(100),email varchar(100))

-------------------------

create table customer_arch (pkid int identity primary key,

id int references customer_test (id),

name varchar(100),dept varchar(100),email varchar(100))

------------------

alter table customer_arch add mode varchar(10)

alter table customer_arch add description varchar(1000)

alter table customer_arch

DROP CONSTRAINT FK__customer_arc__id__53CDB2C9

-----------------------------------------

INSERT INTO customer_test

SELECT 'GAN','SALES','GAN@GMAIL.COM'



DELETE FROM CUSTOMER_TEST

UPDATE CUSTOMER_TEST SET name = name+'P'

TRUNCATE TABLE customer_arch

SELECT * FROM customer_arch

SELECT * FROM customer_test



UPDATE CUSTOMER_TEST

SET NAME = CASE WHEN NAME = 'RAMKI' THEN 'RAM' ELSE NAME END



SELECT CASE WHEN NAME = 'RAM' THEN 'RAMKI' ELSE NAME END

FROM CUSTOMER_TEST

------------------------------------



ALTER TRIGGER TRG_CUSTOMERLOG

ON customer_test

FOR UPDATE, DELETE, INSERT

AS

BEGIN

SELECT * FROM INSERTED

SELECT * FROM DELETED

IF EXISTS (SELECT 1 FROM INSERTED) AND NOT EXISTS (SELECT 1 FROM DELETED)

BEGIN

PRINT 'RECORD INSERTED'

END



ELSE IF EXISTS (SELECT 1 FROM INSERTED I JOIN DELETED D ON D.ID = I.ID

WHERE I.NAME <> D.NAME OR I.DEPT <> D.DEPT OR I.EMAIL <> D.EMAIL)

BEGIN

PRINT 'RECORD UPDATED'

INSERT INTO customer_arch SELECT D.ID,D.NAME,D.DEPT,D.EMAIL, 'UPDATED', NULL

FROM INSERTED I JOIN DELETED D ON D.ID = I.ID

WHERE I.NAME <> D.NAME OR I.DEPT <> D.DEPT OR I.EMAIL <> D.EMAIL



END



ELSE IF NOT EXISTS (SELECT 1 FROM INSERTED) AND EXISTS (SELECT 1 FROM DELETED)

BEGIN

PRINT 'RECORD DELETED'

INSERT INTO customer_arch SELECT D.ID,D.NAME,D.DEPT,D.EMAIL,'DELETED', NULL

FROM DELETED D

END

END

show the report on parameters

=IIF(Parameters!k.Value =
"dollor",Fields!Discount.Value<0.01,Fields!Discount.Value>0.00)

Display the report based on passing the values

create procedure usp_commdish (@month int,@year int)
as
begin

if (@month is null and @year is null)
begin
select count(*),uname,commission_type,
convert(int,datepart(day,date_paid)) as Day,
convert(int,datepart(mm,date_paid) ) as Month,
convert(int,datepart(yyyy,date_paid)) as Year from commissions_dish
WHERE commission_type in ('DVR','DVRBONUS','HD_DVR')
AND payment_amount >= 0
AND uname is not null
--AND datepart(month,date_paid)
--AND datepart(YEAR,DATE_PAID)
group by uname,commission_type,date_paid
end




else if (@month is null)
begin
select count(*),uname,commission_type,
convert(int,datepart(day,date_paid)) as Day,
convert(int,datepart(mm,date_paid) ) as Month,
convert(int,datepart(yyyy,date_paid)) as Year
from commissions_dish
WHERE commission_type in ('DVR','DVRBONUS','HD_DVR')
AND payment_amount >= 0
AND uname is not null
--AND datepart(month,date_paid) =@month
AND datepart(YEAR,DATE_PAID) = @year
group by uname,commission_type,date_paid
end
else if (@year is null)
begin
select count(*),uname,commission_type,
convert(int,datepart(day,date_paid)) as Day,
convert(int,datepart(mm,date_paid) ) as Month,
convert(int,datepart(yyyy,date_paid)) as Year
from commissions_dish
WHERE commission_type in ('DVR','DVRBONUS','HD_DVR')
AND payment_amount >= 0
AND uname is not null
AND datepart(month,date_paid) =@month
--AND datepart(YEAR,DATE_PAID) = @year
group by uname,commission_type,date_paid
end
else
begin
select count(*),uname,commission_type,
convert(int,datepart(day,date_paid)) as Day,
convert(int,datepart(mm,date_paid) ) as Month,
convert(int,datepart(yyyy,date_paid)) as Year
from commissions_dish
WHERE commission_type in ('DVR','DVRBONUS','HD_DVR')

AND payment_amount >= 0
AND uname is not null
AND datepart(month,date_paid) =@month
AND datepart(YEAR,DATE_PAID) = @year
group by uname,commission_type,date_paid
end
end

code for display the colors on headers&footers

Using Reporting Services Embedded Code
Let's start with the fastest way to apply styles to a Reporting Services report, using embedded code. For this example we will only set colour styles, in order to make the example simpler.

The objective is to map the following styles to the following colours

Style Name Colour
Header Blue
Footer Green
BodyText Black
Subtitle Dark Blue

This is how you do it:

Defining Styles
Open an existing report, or create a new report
Access the embedded code of a report by clicking Report/Report Properties in the BIDS menu (you need to have selected either the Data or Layout tabs for this menu option to be available). You can then select the Code tab from the Report Properties dialog – and paste or enter the following code.
Function StyleColor(ByVal Style As String) As String
Select Case UCase(Style)
Case "HEADER"
Return "LightBlue"
Case "FOOTER"
Return "SkyBlue"
Case "MAINTITLE"
Return "Purple"
Case "SUBTITLE"
Return "DarkBlue"
Case Else
Return "White"
End Select
End Function
You should have the following:



Click OK to close the dialog.

OLAP Types

MOLAP
This is the more traditional way of OLAP analysis. In MOLAP, data is stored in a multidimensional cube. The storage is not in the relational database, but in proprietary formats.
Advantages:
• Excellent performance: MOLAP cubes are built for fast data retrieval, and is optimal for slicing and dicing operations.
• Can perform complex calculations: All calculations have been pre-generated when the cube is created. Hence, complex calculations are not only doable, but they return quickly.
Disadvantages:
• Limited in the amount of data it can handle: Because all calculations are performed when the cube is built, it is not possible to include a large amount of data in the cube itself. This is not to say that the data in the cube cannot be derived from a large amount of data. Indeed, this is possible. But in this case, only summary-level information will be included in the cube itself.
• Requires additional investment: Cube technology are often proprietary and do not already exist in the organization. Therefore, to adopt MOLAP technology, chances are additional investments in human and capital resources are needed.
ROLAP
This methodology relies on manipulating the data stored in the relational database to give the appearance of traditional OLAP's slicing and dicing functionality. In essence, each action of slicing and dicing is equivalent to adding a "WHERE" clause in the SQL statement.
Advantages:
• Can handle large amounts of data: The data size limitation of ROLAP technology is the limitation on data size of the underlying relational database. In other words, ROLAP itself places no limitation on data amount.
• Can leverage functionalities inherent in the relational database: Often, relational database already comes with a host of functionalities. ROLAP technologies, since they sit on top of the relational database, can therefore leverage these functionalities.
Disadvantages:
• Performance can be slow: Because each ROLAP report is essentially a SQL query (or multiple SQL queries) in the relational database, the query time can be long if the underlying data size is large.
• Limited by SQL functionalities: Because ROLAP technology mainly relies on generating SQL statements to query the relational database, and SQL statements do not fit all needs (for example, it is difficult to perform complex calculations using SQL), ROLAP technologies are therefore traditionally limited by what SQL can do. ROLAP vendors have mitigated this risk by building into the tool out-of-the-box complex functions as well as the ability to allow users to define their own functions.
HOLAP
HOLAP technologies attempt to combine the advantages of MOLAP and ROLAP. For summary-type information, HOLAP leverages cube technology for faster performance. When detail information is needed, HOLAP can "drill through" from the cube into the underlying relational data.

dates

• "Get Week Start" returns the beginning (00:00:00) of the Monday of the week passed to the function. "Get Week End" returns the end (23:59:59.997) of the Friday of the week passed to the function.
CREATE FUNCTION get_week_start (@date datetime)

RETURNS datetime AS

BEGIN

return dateadd(yyyy, datepart(yyyy,

dateadd(weekday,1-datepart(weekday, @date),@date))-1900, 0)

+ dateadd(dy, datepart(dy,

dateadd(weekday,1-datepart(weekday, @date),@date))-1,0)

END

CREATE FUNCTION get_week_end (@date datetime)

RETURNS datetime AS

BEGIN

return dateadd(yyyy, datepart(yyyy,

dateadd(weekday,7-datepart(weekday, @date),@date))-1900, 0)

+ dateadd(ms, -3,

dateadd(dy, datepart(dy,

dateadd(weekday,7-datepart(weekday, @date),@date)),0) )

END


• "Get Month Start" and "Get Month End" return the start and end of the current month.


CREATE FUNCTION get_month_start (@date datetime)

RETURNS datetime AS

BEGIN

RETURN dateadd(m,datediff(m,0, @date),0)

END

CREATE FUNCTION get_month_end (@date datetime)

RETURNS datetime AS

BEGIN

RETURN dateadd(ms, -3, dateadd (m,datediff(m,0,

dateadd(m,1,@date)),0))

END


• "Get Yesterday Start" and "Get Yesterday End" return the start and end of the day prior to the parameter.


CREATE FUNCTION get_yesterday_start (@today datetime)

RETURNS datetime AS

BEGIN

RETURN dateadd(day, -1, datediff(d,0,@today))

END

CREATE FUNCTION get_yesterday_end (@today datetime)

RETURNS datetime AS

BEGIN

return dateadd(ms, -3, datediff(d,0,@today))

END


• "Get Today Start" and "Get Today End" represent the start and end of the date passed.


CREATE FUNCTION get_today_start (@today datetime)

RETURNS datetime AS

BEGIN

return dateadd(day, 0, datediff(d,0,@today))

END

CREATE FUNCTION get_today_end (@today datetime)

RETURNS datetime AS

BEGIN

return dateadd(ms, -3, datediff(d,0,dateadd(d,1,@today)))

END


• "Get Weekday Start" and "Get Weekday End" return the start and end of the weekday specified within the week passed as date. For example, to get the start and end of Tuesday of the current week, pass the parameters 2 and getdate().


CREATE FUNCTION get_weekday_start (@weekday tinyint,

@date datetime)

RETURNS datetime AS

BEGIN

return dateadd(yyyy, datepart(yyyy,

dateadd(weekday,@weekday-

datepart(weekday, @date),@date))-1900, 0)

+ dateadd(dy, datepart(dy,

dateadd(weekday,@weekday-datepart(weekday, @date),

@date))-1,0)

END

CREATE FUNCTION get_weekday_end (@weekday tinyint,

@date datetime)

RETURNS datetime AS

BEGIN

return dateadd(yyyy, datepart(yyyy,

dateadd(weekday,@weekday-

datepart(weekday, @date),@date))-1900, 0)

+ dateadd(ms, -3,

dateadd(dy, datepart(dy,

dateadd(weekday,@weekday-datepart(weekday, @date),

@date)),0) )

END


• In a similar fashion, the following functions generate dates as indicated in the function name.


CREATE FUNCTION get_year_start (@date datetime)

RETURNS datetime AS

BEGIN

RETURN DATEADD(year,DATEDIFF(year,0, @date),0)

END



CREATE FUNCTION get_tomorrow_noon(@date datetime)

RETURNS datetime

BEGIN

RETURN DATEADD(hh, 12, DATEADD(d,DATEDIFF(d,-1, @date),0))

END



CREATE FUNCTION get_today_noon(@date datetime)

RETURNS datetime

BEGIN

RETURN DATEADD(hh, 12, DATEADD(d,DATEDIFF(d,0, @date),0))

END






Microsoft.com Operations Virtualizes MSDN and TechNet on Hyper-V
Microsoft migrated MSDN to Hyper-V on March 31, 2008, and then followed up with TechNet on April 18, 2008. This article provides further details about testing methods and the results from Hyper-V Beta to RC0 that generated the confidence to fully roll out MSDN and TechNet on Hyper-V in production. »
________________________________________
Virtualization Case Study: Copa Airlines
Always looking to improve server availability and efficiency. Copa Airlines joined a Microsoft Rapid Deployment Program to test Hyper-V to provide a dynamic and reliable virtualization environment and System Center Virtual Machine Manager for the physical to virtual conversions of the chosen servers. The RDP program proved that a Microsoft virtualization solution could be a cost-effective way for Copa to increase business application availability, reduce data center costs, and optimize data center management. »
________________________________________
Virtualization from the Data Center to the Desktop
Integrated virtualization solutions from Microsoft can help you meet evolving demands more effectively as you transform your IT infrastructure from a cost center to a strategic business asset. »
________________________________________
Interoperability Advantages with Windows Server 2008
Learn about the advantages of using Windows Server 2008 with Windows Vista, and find information on how Windows Server 2008 interoperates with other applications and platforms. »
________________________________________
Windows Server 2008 News & Reviews
Keep up to date on the latest Windows Server 2008 news from Microsoft and independent sources worldwide. Here you'll find a compilation of technical reviews, news reports, and press releases about Windows Server 2008 and related products, services, and technologies. »













•An Android in Every Pocket? That's Google's Plan October 24, 2008
•PDC is Not Just the Windows 7 Show October 24, 2008
•How Much Is a Linux Distro Worth? October 22, 2008
•G1 Floats into Market with Fewer Apps October 22, 2008























Webcast: Palm Developer Network Technical Series. The Webcast Series will cover technical topics designed to help you build, debug and market your applications.



Dynamic Default Date Parameters in SQL Server 2000 Reporting Services
By Paul Whitaker
Go to page: Prev 1 2
Selecting Common Dates
These functions are great general purpose date calculators. To better integrate with Reporting Services, I've created a function and stored procedure to populate an RS dataset.
The following is a table-valued function that returns all of the calculated dates. It allows you to SELECT from the list to get only the parameters you need.
CREATE FUNCTION udfCommonDates (@date datetime)

RETURNS @t table (week_start datetime,

week_end datetime,

lastweek_start datetime,

lastweek_end datetime,

month_start datetime,

month_end datetime,

lastmonth_start datetime,

lastmonth_end datetime,

yesterday_start datetime,

yesterday_end datetime,

today_start datetime,

today_end datetime,

thisweek_monday_start datetime,

thisweek_monday_end datetime,

year_start datetime,

tomorrow_noon datetime,

today_noon datetime)

BEGIN

INSERT @t

SELECT

dbo.get_week_start ( @date ) AS week_start,

dbo.get_week_end ( @date ) AS week_end,

dbo.get_week_start ( DATEADD(d, -7, @date ) ) AS lastweek_start,

dbo.get_week_end ( DATEADD(d, -7, @date ) ) AS lastweek_end,

dbo.get_month_start( @date ) AS month_start,

dbo.get_month_end ( @date ) AS month_end,

dbo.get_month_start ( DATEADD(m,-1, @date) ) AS lastmonth_start,

dbo.get_month_end ( DATEADD(m,-1,@date) ) AS lastmonth_end,

dbo.get_yesterday_start ( @date ) AS yesterday_start,

dbo.get_yesterday_end ( @date ) AS yesterday_end,

dbo.get_today_start (@date) AS today_start,

dbo.get_today_end ( @date ) AS today_end,

dbo.get_weekday_start(1,@date) AS thisweek_monday_start,

dbo.get_weekday_end(1,@date) AS thisweek_monday_end,

dbo.get_year_start(@date) AS year_start,

dbo.get_tomorrow_noon(@date) AS TomorrowNoon,

dbo.get_today_noon(@date) AS TodayNoon,RETURN

END


The following stored procedure gets the pertinent dates based on the current date.
CREATE PROCEDURE uspCommonDates AS

begin

set datefirst 1

declare @date datetime

set @date = getdate()

select * from dbo.udfCommonDates(@date)

end


Integrating with Reporting Services
Pulling these dates into Reporting Services via the Report Designer is a breeze. In the Data tab, simply add the uspCommonDates stored procedure as a new Dataset.
Now that you have a Dataset of commonly used dates, they are now available to you to set as Default values for the parameters. Simply select the new dataset and choose whichever "Value field" matches your desired date.

Conclusion
Business intelligence requirements are often bound to relative dates such as the previous day, previous week, or previous month. Generating a list of commonly used dates and setting the appropriate dates as default report parameters can facilitate the easy generation of time-based reports.

Useful Sites

Download the original attachment
Hi Friends,
Here u can get some interesting sites on DWH, Data mining. You an also see links for readings, resources & white papers for the same. I hope this will be helpful for us.
And Ofcourse one of the good place is our Yahoo Group.
Thanks and Regards,
Moderator Team,
Informatica_World
…………………………………………….
Enjoy The Links ….
Data Warehouse White Papers:
Cost of Software Customization (Industry Articles)
Super Data Warehousing Solutions (Industry Articles)
The job forecast: partly cloudy (Industry Articles)
A Case Study in Metadata Harvesting: the NSDL (Academic Articles)
The Role of Network Storage for Data Warehousing (Industry Articles)
CRM Technique: For small industry (Peer Publishing)
Products of the Year 2002 (Industry Articles)
XML meets the data warehouse (Industry Articles)
2003 Survivor's Guide to Business Applications (Industry Articles)
Uncovering Information Hidden in Web Archives (Industry Articles) DW.ITtoolbox.com
http://www.sserve.com/dwintro.asp
An Introduction to Data Warehousing - This white paper introduces data warehousing concepts.

http://www.kenorrinst.com/dwpaper.html
Data Warehousing Technology

http://www.cis.upenn.edu/~sahuguet/OLAP/
An introduction to Data warehousing & OLAP (slides)

http://www.gita.org/chapters/ontario/Data_Ware_ATT.ppt
An Introduction to Data Warehousing (slides)

http://www.cs.man.ac.uk/~franconi/teaching/2001/CS636/CS636-dw-intro.ppt
Introduction to Data Warehousing (slides)

http://www-courses.cs.uiuc.edu/~cs497jh/ppt/lecture_slides.html
Slides for the book "Data Mining: Concepts and Techniques"

http://www.essi-hsv.com/publications/datawarehouse.pdf
Introduction: What is a Data Warehouse?

http://www.pcc.qub.ac.uk/tec/courses/datamining/stu_notes/dm_book_1.html
Data Mining An Introduction, Student Notes

http://www.dwinfocenter.org/
The Data Warehousing Information Center
http://www.dwinfocenter.org/whitepap.html
White Papers on Data Warehousing (Links)

http://otn.oracle.com/idevelop/online/courses/oln/how_to04.html#11.5
Free Data Warehouse Training from Oracle (registration required):
http://www.kdnuggets.com/
Knowledge Discovery Mine

http://www.cs.bham.ac.uk/~anp/TheDataMine.html
The Data Mine

http://www.research.microsoft.com/research/datamine/
Data Mining and Knowledge Discovery (an international journal)

http://research.microsoft.com/datamine/kdd99/
KDD-99: The Fourth International Conference on Knowledge Discovery and Data Mining

http://www.cs.helsinki.fi/research/fdk/
Data mining at the University of Helsinki

http://www3.shore.net/~kht/index.htm#wps
Data Mining White Papers Links

http://www3.shore.net/~kht/dmintro/dmintro.htm
Tutorial - An Introduction to Data Mining and Advanced DSS Technology

http://olap.winf.ruhr-uni-bochum.de/articles.phtml
German OLAP and Data Warehouse Forum - Articles (many are in English)

http://www.dci.com/news/datawarehouse/articles/1998/05/links.htm
Data Warehouse Online Resources: Sites Worth Knowing (Links)

http://www.microsoft.com/technet/SQL/Technote/datawhst.asp
The MS Data Warehousing Strategy

http://hsb.baylor.edu/ramsower/ais.ac.96/papers/gray.htm
DATA WAREHOUSES, OLAP, DATA MINING, AND THE NEW DSS: A Tutorial Presented to AIS'96

http://www.mylab.co.kr/main/html/relevance/Chemo/chemometrics/application_data/Data%20Mining.html
Introduction to Data Mining

http://idm.internet.com/features/datawarehousing.html
A Definition of Data Warehousing - A good 2 page primer on the important aspects of Data Warehousing

http://www.sgroves.demon.co.uk/olaplnks.htm
OLAP Resources

http://www.pilotsw.com/news/olap_white.htm
An Introduction to OLAP: Multidimensional Terminology and Technology

http://www.dw-institute.com/onsite2000/man.htm
Data Warehousing Institute

http://www.datawarehousing.org/
DataWarehousing.org

http://members.aol.com/lpang10473/dms.htm
Data Management Strategies and Technologies

Links from the above site:

Readings:

Corbin, Lisa. Data Warehouses Hit the Web:
http://www.govexec.com/tech/articles/0297info.htm

Data Warehousing Institute. Ten Mistakes to Avoid:
http://www.dw-institute.com/papers/10mistks.htm

Environmental Protection Agency. Envirofacts Warehouse/EnviroMapper:
http://www.epa.gov/enviro/index_java.html

Resources:

Data Warehousing Institute:
Ten Mistakes to Avoid: http://www.dw-institute.com/papers/10mistks.htm
Best Practices: http://www.dw-institute.com/papers/10mistks.htm
Case Studies: http://www.dw-institute.com/cases_a.htm

Datawarehouse.com (DM Review):
http://www.datawarehouse.com/

CIO Magazine Data Warehousing Research Center:
http://www.cio.com/forums/data/

ATG's Technology Guides on Data Warehousing:
http://www.techguide.com/dw/guides.shtml

Data Warehousing Knowledge Center:
http://www.datawarehousing.org/

http://webopedia.internet.com/TERM/d/data_warehouse.html
Data Warehouse Links

get business days

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

ALTER function [dbo].[GetBusinessDays]
(
@StartDate datetime,
@EndDate datetime
)
returns int

/* Release: ?
Created On: ?
Created By: ?
Purpose: Returns the the number of business days in hours format between two dates.
Does not account for holidays.

NOTES:
*/
as
begin

declare @DaysBetween int
declare @BusinessDays int
declare @Cnt int
declare @EvalDate datetime

select @DaysBetween = 0
select @BusinessDays = 0
select @Cnt=0

select @DaysBetween = datediff(Day,@StartDate,@endDate) + 1

while @Cnt < @DaysBetween
begin

select @EvalDate = @StartDate + @Cnt


if ((datepart(dw,@EvalDate) = 1) or (datepart(dw,@EvalDate) = 7))
BEGIN
select @BusinessDays = @BusinessDays + 1
END


select @Cnt = @Cnt + 1
end

return DateDiff(hh,@StartDate,@EndDate)-@BusinessDays*24


end

get business hours

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

ALTER function [dbo].[GetBusinessMinutes] (
@startDate datetime,
@endDate datetime
)
returns int
as
/*
Purpose: Returns the number minutes over business days between @StartDate and @EndDate

Note: This function does not account for holidays, actual open hours (9am-5pm ET), or internationalization.

Modification History
Date By Notes
----------- --------------- ---------------------------------------
10/06/2008 B.Huntley created
10/08/2008 B.Huntley Fixed function to exclude weekends
12/22/2008 C.Gaden Fixed problem when start date was on a weekend
Fixed problem when end date was on a weekend
Fixed problem for daylight savings overlap

*/
BEGIN
DECLARE @daysBetween INT
DECLARE @weekendDays INT
DECLARE @count INT
DECLARE @evalDate DATETIME
declare @returnValue int

SELECT @daysBetween = 0
SELECT @weekendDays = 0
SELECT @count = 0

if (datepart(dw, @startDate) = 1 or datepart(dw, @startDate) = 7) and
(datepart(dw, @endDate) = 1 or datepart(dw, @endDate) = 7) and
(datediff(d, @startDate, @endDate) <= 2)
-- start and end date are on the same weekend; open days is zero
select @returnValue = 0
else
begin
-- account for @startDate occurring on a Saturday or Sunday (do not count these days)
-- if start date is on a weekend make it set to 1 minute after midnight on the following Monday
select @startDate =
case when (DATEPART(dw, @startDate) = 1) then convert(datetime, convert(varchar, month(dateadd(day, 1, @startDate))) + '/' + convert(varchar, day(dateadd(day, 1, @startDate))) + '/' + convert(varchar, year(dateadd(day, 1, @startDate))) + ' 12:01:00 am')
when (DATEPART(dw, @startDate) = 7) then convert(datetime, convert(varchar, month(dateadd(day, 2, @startDate))) + '/' + convert(varchar, day(dateadd(day, 2, @startDate))) + '/' + convert(varchar, year(dateadd(day, 2, @startDate))) + ' 12:01:00 am')
else @startDate
end

-- account for @endDate occurring on a Saturday or Sunday (do not count these days)
-- if end date is on a weekend make it set to 1 minute before midnight on the previous Friday
select @endDate =
case when (DATEPART(dw, @endDate) = 1) then convert(datetime, convert(varchar, month(dateadd(day, -2, @endDate))) + '/' + convert(varchar, day(dateadd(day, -2, @endDate))) + '/' + convert(varchar, year(dateadd(day, -2, @endDate))) + ' 11:59:00 pm')
when (DATEPART(dw, @endDate) = 7) then convert(datetime, convert(varchar, month(dateadd(day, -1, @endDate))) + '/' + convert(varchar, day(dateadd(day, -1, @endDate))) + '/' + convert(varchar, year(dateadd(day, -1, @endDate))) + ' 11:59:00 pm')
else @endDate
end

-- return days between start & end, inclusive of start date
SELECT @daysBetween = DATEDIFF(DAY, @startDate, @endDate) + 1

-- check each day to see if it is a weekend
WHILE @count < @daysBetween
BEGIN
SELECT @evalDate = dateadd(day, @count, @startDate)
IF ((DATEPART(dw, @evalDate) = 1) OR (DATEPART(dw, @evalDate) = 7))
SELECT @weekendDays = @weekendDays + 1
SELECT @count = @count + 1
END

-- calculate number of open minutes (less weekends)
select @returnValue = DATEDIFF(mi, @startDate, @endDate) - @weekendDays * 1440

-- check if negative value occurred; this may happen during daylight savings time-shift
if @returnValue < 0
select @returnValue = 0
end

return @returnValue
END

Function for getting comma seperator

SET
QUOTED_IDENTIFIER ON

GO

/*

Name: CommaSeperator

Description: This function will seperate the string parameters.

Modification History

Date By Description

---------- --------------------- -----------------------------------------------

04/03/2009 Paradigm Infotech Inc. Initial Version created

Copyright [2009] New England BioLabs, Inc. All rights reserved.

*/

create
function [dbo].[CommaSeperator]

(

@stringToBreak varchar
(4000),

@limiter
char(1)

)

returns @list
table (item varchar(4000))

as

begin

if (charindex(@limiter,@stringToBreak) = 0)

begin

insert into @list values (@stringToBreak)

return

end

declare @list1 varchar(4000)

declare @charIndex int

declare @TempItems table (item varchar(4000))

set @charIndex = charindex(@limiter,@stringToBreak)

while len(@stringToBreak) > 0 and @charIndex <> 0

begin

select @list1 = ltrim(left(@stringToBreak,@charIndex - 1))

insert @tempItems select @list1

select @stringToBreak = ltrim(right(@stringToBreak, len(@stringToBreak) - @charIndex))

set @charIndex = charindex(@limiter,@stringToBreak)

end

insert @tempItems select @stringToBreak

insert @list select Item from @tempItems

return

end

Displaying a Pop-up message in SSRS 2005

SSRS 2005 has various limitations but it does have some work-around to perform certain tasks some may think is not possible. Here I am sharing one such experience which I hope will be useful to all SSRS developers out there.

Case In Point:
Requirement was to display a pop-up message box if one of the user entered parameter was not between 1 & 25. As soon as user clicked the ‘View Report’ button, before the report is displayed, this pop-up Confirmation Dialogue box with 'Yes' & 'No' options should be displayed.
FYI: It is also possible to display an error message box, or just plain message box or Confirmation box with 'Yes', 'No' & 'Cancel' and such as you want.

That being said, let’s assume we have a report which accepts a Parameter - an Integer from the user. If user enters a number less than 1 or more than 25, a pop-up message dialogue will appear asking user for confirmation. Something like - "You selected '30'. Are you sure you want to Continue?”

If user still decides to run the report and clicks "Yes", we should run the report. If user clicks "No", the report will not be displayed, instead a message box will be displayed asking user to correct their parameter supplied. In any case user enters a number between 1 and 25, it is valid and therefore no pop-up is displayed but just the report. You can of course change any of this functionality to suite your need.

Solution:
Let's get started by creating a parameter, say a parameter name ‘Number’, of Integer type. Under its Default values check Non-queried and set a value of 1, you can modify according to your requirement.



Now let’s create another parameter ‘IsValidNum’ of type Boolean. This will determine if the user entered number is between 1 and 25. Make this second parameter a Hidden parameter. Based on the value of this Hidden parameter IsValidNum, we will control what user gets to see.




We want to make sure our report is inside a single control. Say for example, if you have various Textboxes and may be couple of Tables, you would want to include all these inside one control – may be a Rectangle or a Listbox, or simply a single Table. We would then want to set the visibility of this control to Hidden - only if our IsValidNum parameter returns false.

Let’s name our main control “RprtCtrl”.

Go to its properties > Visibility > Hidden and change the expression to:
= Not(Parameter!IsValidNum.Value)



The whole idea of building the report as a single control is to control what gets displayed based on our parameter - IsValidNum. Of course, you do not have to make it a single control, but in that case you will have to change the “Hidden” property of each and every control based on this parameter. Now let us put a Textbox outside our main control. This Textbox will display the message to the user saying something like “Please enter the number between 1 and 25”. The Hidden property of this Textbox will be just opposite to that of our main control. So if the parameter ‘IsValidNum’ returns TRUE, this Textbox’s Hidden property will be set to FALSE and that of the main control to TRUE. Thus showing the Textbox and hiding the report.

Let’s name our textbox “MsgTxtBx”.

Go to its properties > Visibility > Hidden and change the expression to:
= Parameter!IsValidNum.Value



This should assure that you see your Report only when the user wants to or only if user selects the value between 1 and 25. In any other case, user gets a message asking to enter the number between 1 and 25. Of course based on our parameter – ‘IsValidNum’.

Okay, so how do we decide the Value for ‘IsValidNum’ parameter?
It’s simple right? If the user enter the value between 1 and 25 for the parameter ‘Number’ it is TRUE and for all others value it is FALSE.

Not exactly! Remember value of the number decides if a Message Box should be popped-up or not and then based on user’s decision i.e. whether they click ‘Yes’ or ‘No’, ‘IsValidNum’ gets its value set. So let us now write a method to handle this functionality.
Our goal of this function would be to check the value of the parameter Number and if it is not between 1 and 25, display a pop-up message asking user if they want to continue running the report. If user clicks ‘Yes’ - we display the report, if ‘No’ - a message will be displayed asking user to simply enter the correct value.
FYI: We are displaying the message to enter the correct value in a Textbox here, but you could also display the same message in a pop-up instead.

To handle this, let us write a VB function.

Go to Report Properties and under the Code tab write the following VB function:

Function CheckNum(NumEntered as Integer) as Boolean

Dim prompt as String
Dim usrResponse As MsgBoxResult

prompt = ""
usrResponse = MsgBoxResult.No

If (NumEntered > 25 OR NumEntered < 1) Then prompt = "You entered " & Str(NumEntered) _ & ". Are you sure you want to continue?" End If If prompt <> "" Then
usrResponse = MsgBox(prompt,4,"Message Box Title" )

If usrResponse = MsgBoxResult.Yes Then
Return TRUE
Else
Return FALSE
End If
Else
Return TRUE
End If

End Function

This function accepts an Integer as a parameter and returns a Boolean value. Every time the value of the parameter is not between 1 & 25, it creates a String prompt which is just asking user for confirmation and the confirmation prompt is displayed on a pop-up message box. Based on whether user clicks ‘Yes’ or ‘No’, the function returns the Boolean value. The function returns ‘TRUE’ if its parameter value is between 1 & 25.
FYI: The MsgBox Function is explained here http://msdn.microsoft.com/en-us/library/139z2azd(VS.80).aspx for more information.


Now how do we trigger this function call?
This is the trickiest part. We want the pop-up before report is displayed. So this should be triggered with the parameter.

Let’s go back to our hidden report parameter ‘IsValidNum’. Under Default values, check Non-queried and edit the expression as:
=Code.CheckNum(Parameters!Number.Value)



This will assign the boolean value returned from our function to this hidden parameter ‘IsValidNum’.

Now run the report if you enter value less than 1 or greater than 25 you should now get a pop-up.




This concept can be used to validate your report parameters and displaying user with friendly pop-up message. Enjoy!!

To find out the quarter start date and end date

USE [reddy]
GO
/****** Object: StoredProcedure [dbo].[usp_GetQuaterStartAndEndDates] Script Date: 02/26/2011 23:41:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_GetQuaterStartAndEndDates]
AS
BEGIN
Declare @Q_StartDate Datetime
Declare @Q_EndDate Datetime
Declare @Qno Int

SELECT @Qno = DATEPART(QQ,GETDATE())

IF @Qno = 1
BEGIN
SET @Q_StartDate = '01-01-' + Convert(Varchar(10),(DATEPART(YY,GETDATE())))
SET @Q_EndDate = '03-31-' + Convert(Varchar(10),(DATEPART(YY,GETDATE())))
END
ELSE IF @Qno = 2
BEGIN
SET @Q_StartDate = '04-01-' + Convert(Varchar(10),(DATEPART(YY,GETDATE())))
SET @Q_EndDate = '06-30-' + Convert(Varchar(10),(DATEPART(YY,GETDATE())))
END
ELSE IF @Qno = 3
BEGIN
SET @Q_StartDate = '07-01-' + Convert(Varchar(10),(DATEPART(YY,GETDATE())))
SET @Q_EndDate = '09-30-' + Convert(Varchar(10),(DATEPART(YY,GETDATE())))
END
ELSE IF @Qno = 4
BEGIN
SET @Q_StartDate = '10-01-' + Convert(Varchar(10),(DATEPART(YY,GETDATE())))
SET @Q_EndDate = '12-31-' + Convert(Varchar(10),(DATEPART(YY,GETDATE())))
END

SELECT @Q_StartDate AS BEGINNINGDATE, @Q_EndDate as ENDDATE
END

recussive stored procedure

create
procedure proc_all(@eno int,@add int output)

as

begin

select
@add=@eno+5

return

end

create
procedure proc_1(@eno int,@mul int output)

as

begin

select
@mul=@eno*5

return

end

alter
procedure proc_2(@eno int)

as

begin

declare
@x int

declare
@mul int

declare
@add int

--declare @add int

exec
proc_all @eno,@add output

exec
proc_1 @eno,@mul output

select
@x=@add+@mul

select
@x as result

return

end

exec
proc_2 8