Skip to content

Instantly share code, notes, and snippets.

@stevomccormack
Last active May 15, 2018 18:57
Show Gist options
  • Save stevomccormack/67dbae5f71a460fa6da1cc2216db35b1 to your computer and use it in GitHub Desktop.
Save stevomccormack/67dbae5f71a460fa6da1cc2216db35b1 to your computer and use it in GitHub Desktop.
CodeSmith Tools - Stored Procedures (CRUD) Generator - Source & Output for all DML and Select cases for all web development use cases (more available - ommitted).
--region Drop Existing Procedures
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertAthlete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[InsertAthlete]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertAllAthlete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[InsertAllAthlete]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateAthlete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UpdateAthlete]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateAllAthlete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UpdateAllAthlete]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteAthlete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DeleteAthlete]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteAllAthletes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DeleteAllAthletes]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteAthletesByForeignKey]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DeleteAthletesByForeignKey]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteAthletesBy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DeleteAthletesBy]
--endregion
GO
--region [dbo].[InsertAthlete]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[InsertAthlete]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[InsertAthlete]
-- primary key
@ProfileId int,
-- non primary key columns
@AthleteType int,
@AthleteClass int,
@HeightInCentimeters int,
@HeightInInches float,
@WeightInKilograms int,
@WeightInPounds int,
@YearsInSport int,
@YearsAsPro int,
@RepresentCountryName nvarchar(50),
@RepresentCountryIso2Code nvarchar(3),
@CoachFullName nvarchar(100),
@CoachTitle nvarchar(100),
@CoachUrl nvarchar(100),
@AgentFullName nvarchar(100),
@AgentTitle nvarchar(100),
@AgentUrl nvarchar(100),
@AgencyName nvarchar(100),
@AgencyUrl nvarchar(100),
@PersonalBests nvarchar(100),
@OrderIndex int,
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check if key already exists.
* ------------------------------------------------------------- */
IF EXISTS
(
SELECT
NULL
FROM
[dbo].[Athlete]
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
-- return already exists
RETURN -1
END
BEGIN
/* -------------------------------------------------------------
* DML Insert w/ pk specified.
* ------------------------------------------------------------- */
INSERT INTO [dbo].[Athlete]
(
[dbo].[Athlete].[ProfileId], /* pk */
[dbo].[Athlete].[AthleteType],
[dbo].[Athlete].[AthleteClass],
[dbo].[Athlete].[HeightInCentimeters],
[dbo].[Athlete].[HeightInInches],
[dbo].[Athlete].[WeightInKilograms],
[dbo].[Athlete].[WeightInPounds],
[dbo].[Athlete].[YearsInSport],
[dbo].[Athlete].[YearsAsPro],
[dbo].[Athlete].[RepresentCountryName],
[dbo].[Athlete].[RepresentCountryIso2Code],
[dbo].[Athlete].[CoachFullName],
[dbo].[Athlete].[CoachTitle],
[dbo].[Athlete].[CoachUrl],
[dbo].[Athlete].[AgentFullName],
[dbo].[Athlete].[AgentTitle],
[dbo].[Athlete].[AgentUrl],
[dbo].[Athlete].[AgencyName],
[dbo].[Athlete].[AgencyUrl],
[dbo].[Athlete].[PersonalBests],
[dbo].[Athlete].[OrderIndex]
)
VALUES
(
@ProfileId,
@AthleteType,
@AthleteClass,
@HeightInCentimeters,
@HeightInInches,
@WeightInKilograms,
@WeightInPounds,
@YearsInSport,
@YearsAsPro,
@RepresentCountryName,
@RepresentCountryIso2Code,
@CoachFullName,
@CoachTitle,
@CoachUrl,
@AgentFullName,
@AgentTitle,
@AgentUrl,
@AgencyName,
@AgencyUrl,
@PersonalBests,
@OrderIndex
)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''[dbo].[InsertAthlete]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[InsertAthlete]''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- return success(0)
RETURN 0
--endregion
GO
--region [dbo].[InsertAllAthlete]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[InsertAllAthlete]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
--endregion
GO
--region [dbo].[UpdateAthlete]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[UpdateAthlete]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[UpdateAthlete]
-- primary key(s)
@ProfileId int,
-- columns
@AthleteType int,
@AthleteClass int,
@HeightInCentimeters int,
@HeightInInches float,
@WeightInKilograms int,
@WeightInPounds int,
@YearsInSport int,
@YearsAsPro int,
@RepresentCountryName nvarchar(50),
@RepresentCountryIso2Code nvarchar(3),
@CoachFullName nvarchar(100),
@CoachTitle nvarchar(100),
@CoachUrl nvarchar(100),
@AgentFullName nvarchar(100),
@AgentTitle nvarchar(100),
@AgentUrl nvarchar(100),
@AgencyName nvarchar(100),
@AgencyUrl nvarchar(100),
@PersonalBests nvarchar(100),
@OrderIndex int,
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
[dbo].[Athlete]
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Update by pk
* ------------------------------------------------------------- */
UPDATE
[dbo].[Athlete]
SET
[AthleteType] = @AthleteType,
[AthleteClass] = @AthleteClass,
[HeightInCentimeters] = @HeightInCentimeters,
[HeightInInches] = @HeightInInches,
[WeightInKilograms] = @WeightInKilograms,
[WeightInPounds] = @WeightInPounds,
[YearsInSport] = @YearsInSport,
[YearsAsPro] = @YearsAsPro,
[RepresentCountryName] = @RepresentCountryName,
[RepresentCountryIso2Code] = @RepresentCountryIso2Code,
[CoachFullName] = @CoachFullName,
[CoachTitle] = @CoachTitle,
[CoachUrl] = @CoachUrl,
[AgentFullName] = @AgentFullName,
[AgentTitle] = @AgentTitle,
[AgentUrl] = @AgentUrl,
[AgencyName] = @AgencyName,
[AgencyUrl] = @AgencyUrl,
[PersonalBests] = @PersonalBests,
[OrderIndex] = @OrderIndex
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''[dbo].[UpdateAthlete]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[UpdateAthlete]''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[UpdateAllAthlete]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[UpdateAllAthlete]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[UpdateAllAthlete]
-- primary key(s)
@ProfileId int,
-- columns
@AthleteType int,
@AthleteClass int,
@HeightInCentimeters int,
@HeightInInches float,
@WeightInKilograms int,
@WeightInPounds int,
@YearsInSport int,
@YearsAsPro int,
@RepresentCountryName nvarchar(50),
@RepresentCountryIso2Code nvarchar(3),
@CoachFullName nvarchar(100),
@CoachTitle nvarchar(100),
@CoachUrl nvarchar(100),
@AgentFullName nvarchar(100),
@AgentTitle nvarchar(100),
@AgentUrl nvarchar(100),
@AgencyName nvarchar(100),
@AgencyUrl nvarchar(100),
@PersonalBests nvarchar(100),
@OrderIndex int,
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
[dbo].[Athlete]
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Update by pk
* ------------------------------------------------------------- */
UPDATE
[dbo].[Athlete]
SET
[AthleteType] = @AthleteType,
[AthleteClass] = @AthleteClass,
[HeightInCentimeters] = @HeightInCentimeters,
[HeightInInches] = @HeightInInches,
[WeightInKilograms] = @WeightInKilograms,
[WeightInPounds] = @WeightInPounds,
[YearsInSport] = @YearsInSport,
[YearsAsPro] = @YearsAsPro,
[RepresentCountryName] = @RepresentCountryName,
[RepresentCountryIso2Code] = @RepresentCountryIso2Code,
[CoachFullName] = @CoachFullName,
[CoachTitle] = @CoachTitle,
[CoachUrl] = @CoachUrl,
[AgentFullName] = @AgentFullName,
[AgentTitle] = @AgentTitle,
[AgentUrl] = @AgentUrl,
[AgencyName] = @AgencyName,
[AgencyUrl] = @AgencyUrl,
[PersonalBests] = @PersonalBests,
[OrderIndex] = @OrderIndex
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''[dbo].[UpdateAllAthlete]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[UpdateAllAthlete]''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
-------------------------------------------------------------------------
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[DeleteAllAthletes]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[DeleteAllAthletes]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[DeleteAllAthletes]
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
[dbo].[Athlete]
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Delete all
* ------------------------------------------------------------- */
DELETE FROM
[dbo].[Athlete]
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''[dbo].[DeleteAllAthletes]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected < 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[DeleteAllAthletes]''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[DeleteAthlete]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[DeleteAthlete]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[DeleteAthlete]
-- primary key(s)
@ProfileId int,
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
[dbo].[Athlete]
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Delete by pk
* ------------------------------------------------------------- */
DELETE FROM
[dbo].[Athlete]
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''[dbo].[DeleteAthlete]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[DeleteAthlete]''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[DeleteAthletesByForeignKey]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[DeleteAthletesByForeignKey]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[DeleteAthletesByForeignKey]
-- optional keys
@ProfileId int = NULL,
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Ensure optional parameters provided
* ------------------------------------------------------------- */
IF
(
@ProfileId IS NULL
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Must provide at least one optional parameter for ''[dbo].[DeleteAthletesByForeignKey]''', 15, 1)
RETURN -201 -- expecting parameter code!
END
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
[dbo].[Athlete]
WHERE
(@ProfileId IS NULL OR [dbo].[Athlete].[ProfileId] = @ProfileId)
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Delete by fk.
* ------------------------------------------------------------- */
DELETE FROM
[dbo].[Athlete]
WHERE
(@ProfileId IS NULL OR [dbo].[Athlete].[ProfileId] = @ProfileId)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''[dbo].[DeleteAthletesByForeignKey]''', 10, 1)
RETURN @ErrStatus
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[DeleteAthletesBy]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[DeleteAthletesBy]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[DeleteAthletesBy]
-- optional keys, bits
@ProfileId int = NULL,
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Ensure optional parameters provided
* ------------------------------------------------------------- */
IF
(
@ProfileId IS NULL
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Must provide at least one optional parameter for ''[dbo].[DeleteAthletesBy]''', 15, 1)
RETURN -201 -- expecting parameter code!
END
/* -------------------------------------------------------------
* Check exists
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
[dbo].[Athlete]
WHERE
(@ProfileId IS NULL OR [dbo].[Athlete].[ProfileId] = @ProfileId)
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* Delete by keys, bits
* ------------------------------------------------------------- */
DELETE FROM
[dbo].[Athlete]
WHERE
(@ProfileId IS NULL OR [dbo].[Athlete].[ProfileId] = @ProfileId)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''[dbo].[DeleteAthletesBy]''', 10, 1)
RETURN @ErrStatus
END
END
-- commit transaction.
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Drawing;
using Sytem.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Repository.Pattern.Ef6;
using Repository.Pattern.Ef6.Factories;
using Repository.Pattern.Infrastructure;
using Repository.Pattern.UnitOfWork;
using Repository.Pattern.Repositories;
using GemBox.Spreadsheet;
using MWeb.Web.UI;
using MWeb.Web.UI.Repository;
using MWeb.Data.Model;
using MWeb.Data.Repository;
namespace MWeb.Website.Administration
{
/// <summary>
/// AthletesPage
/// </summary>
public partial class AthletesPage : MWeb.Web.UI.Repository.RepositoryEntityPagedListModifierBasePage<Athlete>
{
#region Constructors
public AthletesPage() :
base()
{
//event handlers
this.Init += new System.EventHandler( this.Page_Init );
this.Load += new System.EventHandler( this.Page_Load );
this.PreRender += new System.EventHandler( this.Page_PreRender );
//data context.
var dataContext = new SolariEnergy.Data.Entity.SolariEnergyContext();
//setup custom repository
UnitOfWork unitOfWork = null;
var factories = new Dictionary<Type, Func<dynamic>>
{
{
typeof (AthleteRepository),
() => new AthleteRepository(dataContext, unitOfWork)
}
};
//uow & repositories.
var repositoryProvider = new RepositoryProvider( new RepositoryFactories( factories ) );
unitOfWork = new UnitOfWork( dataContext, repositoryProvider );
var repository = new AthleteRepository( dataContext, unitOfWork );
repositoryProvider.SetRepository<AthleteRepository>(repository);
//members.
this.UnitOfWork = unitOfWork;
this.Repository = repository;
}
#endregion
#region Page Events
/// <summary>
/// Init Event
/// </summary>
/// <remarks>Viewstate information is not available at this stage.</remarks>
private void Page_Init(object sender, System.EventArgs e)
{
}
/// <summary>
/// Load Event
/// </summary>
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//default sort.
this.SortBy = "OrderIndex";
this.SortDirection = MWeb.Web.UI.SortDirection.Asc;
//setup filters.
this.SetupFilters();
//bind grid.
this.BindGrid();
}
}
/// <summary>
/// PreRender Event
/// </summary>
private void Page_PreRender(object sender, System.EventArgs e)
{
//search textbox.
this.SearchTextBox.Text = this.SearchText;
}
#endregion
#region Methods
#region Setup
/// <summary>
/// Setup filters from querystring
/// </summary>
private void SetupFilters()
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["profileid"]))
{
this.ProfileId = Convert.ToInt32(Server.UrlDecode(Request.QueryString["profileid"]));
}
}
#endregion
#region Bind Methods
private void BindGrid()
{
new Action( async () =>
{
//get list.
var entityList = await this.GetPagedList( this.FilterExpression, this.SortDelegate, this.IncludeExpressionList, this.PageNumber, this.PageSize );
////setup grid view.
this.DefaultGridView.PageIndex = this.PageNumber - 1;
this.DefaultGridView.PageSize = this.PageSize;
this.DefaultGridView.DataSource = entityList;
this.DefaultGridView.DataBind();
//update page heading
this.PageHeading += "<small>" + this.TotalCount + " record" + ((this.TotalCount == 1) ? string.Empty : "s") + " found.</small>";
//update filtered heading
this.FilteredMessage.Visible = false;
if (this.IsFiltered)
{
this.FilteredMessage.Visible = true;
}
} ).Invoke();
}
#endregion
#region Filter Methods
/// <summary>
/// Creates and return the querystring used for filtering records.
/// </summary>
protected override string CreateFilterQueryString()
{
//base query.
string filterQuery = base.CreateFilterQueryString();
//create query
bool hasQuery = (filterQuery.IndexOf( "?" ) != -1);
string filters = (hasQuery ? string.Empty : "?");
//dropdown filters.
if (this.ProfileId != 0)
{
if (hasQuery) filters += "&";
filters += "profileid=" + Server.UrlEncode( this.ProfileId.ToString() );
}
//return combined query.
return filterQuery + filters;
}
#endregion
#endregion
#region Properties
#region ISearchControl, IFilterControl, ISortControl Properties
/// <summary>
/// Returns the search expression used with <code>GetPagedList</code>
/// </summary>
public override Expression<Func<Athlete, bool>> SearchExpression
{
get
{
if (this.HasSearchText)
{
switch(this.SearchType)
{
case SearchType.StartsWith:
{
return
(
f => f.RepresentCountryName.StartsWith( this.SearchText ) ||
f.RepresentCountryIso2Code.StartsWith( this.SearchText ) ||
f.CoachFullName.StartsWith( this.SearchText ) ||
f.CoachTitle.StartsWith( this.SearchText ) ||
f.CoachUrl.StartsWith( this.SearchText ) ||
f.AgentFullName.StartsWith( this.SearchText ) ||
f.AgentTitle.StartsWith( this.SearchText ) ||
f.AgentUrl.StartsWith( this.SearchText ) ||
f.AgencyName.StartsWith( this.SearchText ) ||
f.AgencyUrl.StartsWith( this.SearchText ) ||
f.PersonalBests.StartsWith( this.SearchText )
);
}
case SearchType.Contains:
return
(
f => f.RepresentCountryName.Contains( this.SearchText ) ||
f.RepresentCountryIso2Code.Contains( this.SearchText ) ||
f.CoachFullName.Contains( this.SearchText ) ||
f.CoachTitle.Contains( this.SearchText ) ||
f.CoachUrl.Contains( this.SearchText ) ||
f.AgentFullName.Contains( this.SearchText ) ||
f.AgentTitle.Contains( this.SearchText ) ||
f.AgentUrl.Contains( this.SearchText ) ||
f.AgencyName.Contains( this.SearchText ) ||
f.AgencyUrl.Contains( this.SearchText ) ||
f.PersonalBests.Contains( this.SearchText )
);
}
case SearchType.Excludes:
return
(
f => !f.RepresentCountryName.Contains( this.SearchText ) ||
!f.RepresentCountryIso2Code.Contains( this.SearchText ) ||
!f.CoachFullName.Contains( this.SearchText ) ||
!f.CoachTitle.Contains( this.SearchText ) ||
!f.CoachUrl.Contains( this.SearchText ) ||
!f.AgentFullName.Contains( this.SearchText ) ||
!f.AgentTitle.Contains( this.SearchText ) ||
!f.AgentUrl.Contains( this.SearchText ) ||
!f.AgencyName.Contains( this.SearchText ) ||
!f.AgencyUrl.Contains( this.SearchText ) ||
!f.PersonalBests.Contains( this.SearchText )
);
}
case SearchType.EndsWith:
return
(
f => f.RepresentCountryName.EndsWith( this.SearchText ) ||
f.RepresentCountryIso2Code.EndsWith( this.SearchText ) ||
f.CoachFullName.EndsWith( this.SearchText ) ||
f.CoachTitle.EndsWith( this.SearchText ) ||
f.CoachUrl.EndsWith( this.SearchText ) ||
f.AgentFullName.EndsWith( this.SearchText ) ||
f.AgentTitle.EndsWith( this.SearchText ) ||
f.AgentUrl.EndsWith( this.SearchText ) ||
f.AgencyName.EndsWith( this.SearchText ) ||
f.AgencyUrl.EndsWith( this.SearchText ) ||
f.PersonalBests.EndsWith( this.SearchText )
);
}
default:
break
}
}
return null;
}
}
/// <summary>
/// Returns the filter expression list used with <code>GetPagedList</code>
/// </summary>
public override List<Expression<Func<Athlete, bool>>> FilterExpressionList
{
get
{
if (this.IsFiltered)
{
var filterExpressionList = new List<Expression<Func<Athlete, bool>>>();
//boolean filters.
//key filters.
if (!string.IsNullOrWhiteSpace( this.ProfileId ))
{
Expression<Func<Athlete, bool>> keyFilterExp1 = (f => f.ProfileId == this.ProfileId); //ProfileId
filterExpressionList.Add( keyFilterExp1 );
}
return filterExpressionList;
}
return null;
}
}
/// <summary>
/// Returns the include expression list used with <code>GetPagedList</code>
/// </summary>
public override List<Expression<Func<Athlete, object>>> IncludeExpressionList
{
get
{
var includeExpressionList = new List<Expression<Func<Athlete, object>>>();
//Profile
Expression<Func<Athlete, object>> includeExp1 = (i => i.Profile);
includeExpressionList.Add( includeExp1 );
return includeExpressionList;
}
}
#endregion
#region UI Filter Properties
#region DropDownList Filter Properties
/// <summary>
/// ProfileId
/// </summary>
public int? ProfileId
{
get
{
object o = ViewState["ProfileId"];
return (null == o) ? 0 : (int)o;
}
set
{
if (this.ProfileId != value)
{
ViewState["ProfileId"] = value;
//set filter
this.IsFiltered = this.IsFiltered || this.ProfileId.HasValue;
}
}
}
#endregion
#endregion
#endregion
#region Event Handlers
#region Html Button Event Handlers
/// <summary>
/// Html Button Click Event Handler.
/// </summary>
protected void HtmlButton_ServerClickEventHandler(object sender, System.EventArgs e)
{
HtmlButton htmlButton = (HtmlButton)sender;
if (sender.Equals( this.CreateButton ))
{//add item.
Response.Redirect( "./modify" + this.FileName, false );
}
else if (sender.Equals( this.ResetButton ))
{//reset
Response.Redirect( this.FileName, false );
}
else if (sender.Equals( this.SearchButton ))
{//search.
Page.Validate( "search-group" );
if (Page.IsValid)
{
//filter.
this.SearchText = this.SearchTextBox.Text.Trim();
//bind.
this.BindGrid();
}
}
else if (sender.Equals( this.ExportButton ))
{//export list.
this.Page.RegisterAsyncTask( new PageAsyncTask( async ( t ) =>
{
var entityList = await this.GetPagedList( this.FilterExpression, this.SortDelegate, null, this.PageNumber, this.PageSize );
if (entityList.Count > 0)
{
//create excel file.
SpreadsheetInfo.SetLicense( "FREE-LIMITED-KEY" );
ExcelFile excelFile = new ExcelFile();
excelFile.DefaultFontName = "Calibri";
//create worksheet
ExcelWorksheet excelWorksheet = excelFile.Worksheets.Add( Path.GetFileNameWithoutExtension( this.FileName ) );
//sort columns
var sortColumnIndex = 0;
var sortThenColumnIndex = 0;
//header rows
var cellIndex = 0;
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "AthleteType";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "AthleteClass";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "HeightInCentimeters";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "HeightInInches";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "WeightInKilograms";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "WeightInPounds";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "YearsInSport";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "YearsAsPro";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "RepresentCountryName";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "RepresentCountryIso2Code";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "CoachFullName";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "CoachTitle";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "CoachUrl";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "AgentFullName";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "AgentTitle";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "AgentUrl";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "AgencyName";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "AgencyUrl";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "PersonalBests";
excelWorksheet.Rows[0].Cells[cellIndex++].Value = "OrderIndex";
//set column count.
var columnCount = cellIndex;
//cell ranges.
var allCellsRange = excelWorksheet.Cells.GetSubrangeAbsolute( 0, 0, entityList.Count-1, columnCount - 1 );
var headerCellsRange = excelWorksheet.Cells.GetSubrangeAbsolute( 0, 0, 0, columnCount - 1 );
var contentCellsRange = excelWorksheet.Cells.GetSubrangeAbsolute( 1, 0, entityList.Count, columnCount - 1 );
//find sort column
cellIndex = 0;
foreach (var cell in headerCellsRange)
{
if (this.SortBy == cell.Value.ToString())
{
sortColumnIndex = cellIndex;
}
else if (this.ThenBy == cell.Value.ToString())
{
sortThenColumnIndex = cellIndex;
}
if (sortColumnIndex > 0 && sortThenColumnIndex > 0)
break;
cellIndex++;
}
//bind entities
var currentRow = 1;
foreach (var entity in entityList)
{
cellIndex = 0;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.AthleteType.ToString();
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.AthleteClass.ToString();
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.HeightInCentimeters.ToString();
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.HeightInInches.ToString("0.00");
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.WeightInKilograms.ToString();
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.WeightInPounds.ToString();
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.YearsInSport.ToString();
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.YearsAsPro.ToString();
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.RepresentCountryName;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.RepresentCountryIso2Code;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.CoachFullName;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.CoachTitle;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.CoachUrl;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.AgentFullName;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.AgentTitle;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.AgentUrl;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.AgencyName;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.AgencyUrl;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.PersonalBests;
excelWorksheet.Rows[currentRow].Cells[cellIndex++].Value = entity.OrderIndex.ToString();
currentRow++;
}
//freeze header row.
excelWorksheet.Panes = new WorksheetPanes( PanesState.Frozen, 0, 1, "A1", PanePosition.BottomLeft );
//auto fit
//var maxColumns = excelWorksheet.CalculateMaxUsedColumns();
for (int i = 0; i < columnCount; i++)
{
excelWorksheet.Columns[i].AutoFit( 1, excelWorksheet.Rows[1], excelWorksheet.Rows[entityList.Count] );
}
//print area.
excelWorksheet.NamedRanges.SetPrintArea( allCellsRange );
excelWorksheet.PrintOptions.PrintGridlines = true;
//sorting
//contentCellsRange.Merged = true;
contentCellsRange.Sort( new SortDescription( sortColumnIndex ), new SortDescription( sortThenColumnIndex ) );
//cell stylings.
CellStyle style = new CellStyle( excelFile );
style.HorizontalAlignment = HorizontalAlignmentStyle.Left;
style.VerticalAlignment = VerticalAlignmentStyle.Center;
style.Font.Color = System.Drawing.Color.Black;
style.WrapText = true;
style.Borders.SetBorders( MultipleBorders.Top | MultipleBorders.Left | MultipleBorders.Right | MultipleBorders.Bottom, System.Drawing.Color.Black, LineStyle.Thin );
contentCellsRange.Style = style;
//filename.
string filename = Path.ChangeExtension( this.FileName, ".csv" );
excelFile.Save( HttpContext.Current.Response, filename, SaveOptions.CsvDefault );
}
} ) );
}
}
#endregion
#region Paging Event Handlers
/// <summary>
/// Paging Link Event Handler.
/// </summary>
//protected void PagingLink_ServerClickEventHandler( object sender, System.EventArgs e )
//{
// HtmlAnchor htmlLink = (HtmlAnchor)sender;
// int pageNumber = Convert.ToInt32( htmlLink.Attributes["data-page-number"] );
// this.PageNumber = pageNumber;
// //rebind
// this.BindGrid();
//}
/// <summary>
/// PageSize Link Event Handler.
/// </summary>
protected void PageSizeLink_ServerClickEventHandler( object sender, System.EventArgs e )
{
HtmlAnchor htmlLink = (HtmlAnchor)sender;
int pageSize = Convert.ToInt32( htmlLink.Attributes["data-page-size"] );
this.PageSize = pageSize;
//rebind.
this.BindGrid();
}
#endregion
#region GridView Event Handlers
protected void GridView_RowDataBoundEventHandler(object sender, GridViewRowEventArgs e)
{
GridView gridView = (GridView)sender;
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
DataControlFieldHeaderCell thHeaderCell = (DataControlFieldHeaderCell)e.Row.Cells[i];
if (e.Row.Cells[i].Controls != null && e.Row.Cells[i].Controls.Count > 0)
{
if (e.Row.Cells[i].Controls[0].GetType().BaseType == typeof( System.Web.UI.WebControls.LinkButton ))
{
System.Web.UI.WebControls.LinkButton linkButton = (System.Web.UI.WebControls.LinkButton)e.Row.Cells[i].Controls[0];
//add attribute to all links to store current sort direction.
switch (this.SortDirection)
{
case MWeb.Web.UI.SortDirection.Asc:
{
linkButton.Attributes.Add( "data-sort-direction", "sort-asc" );
break;
}
case MWeb.Web.UI.SortDirection.Desc:
{
linkButton.Attributes.Add( "data-sort-direction", "sort-desc" );
break;
}
default:
break;
}
//add sort direction to current.
if (!string.IsNullOrWhiteSpace( this.SortBy ) && thHeaderCell.ContainingField.SortExpression.ToLower() == this.SortBy.ToLower())
{
switch (this.SortDirection)
{
case MWeb.Web.UI.SortDirection.Asc:
{
linkButton.CssClass = "sort-asc";
break;
}
case MWeb.Web.UI.SortDirection.Desc:
{
linkButton.CssClass = "sort-desc";
break;
}
default:
break;
}
}
}
}
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
var entity = (Athlete)e.Row.DataItem;
//TODO: Nested entities
//confirm delete
foreach (DataControlField field in ((GridView)sender).Columns)
{
Type fieldType = field.GetType();
/*
if (this.ConfirmDelete && fieldType.Name == "CommandField" && ((CommandField)field).ShowDeleteButton)
{//confirm delete.
//int itemName = (int)DataBinder.Eval(dataItem, "ProfileId");
ImageButton btnDelete = (ImageButton)e.Row.Cells[gridView.Columns.IndexOf(field)].Controls[0];
btnDelete.OnClientClick = "if (!window.confirm(\"Are you sure you want to delete this item?\")) return false;";
}
*/
}
}
}
protected void GridView_PageIndexChangedEventHandler(object sender, System.EventArgs e)
{
GridView gridView = (GridView)sender;
//TODO: Update pager.
//set page.
this.PageNumber = gridView.PageIndex + 1;
//rebind.
this.BindGrid();
}
protected void GridView_RowEditingEventHandler(object sender, GridViewEditEventArgs e)
{
GridView gridView = (GridView)sender;
gridView.EditIndex = e.NewEditIndex;
//rebind.
this.BindGrid();
}
protected void GridView_RowCancelingEditEventHandler(object sender, GridViewCancelEditEventArgs e)
{
GridView gridView = (GridView)sender;
//edit index.
gridView.EditIndex = -1;
//rebind.
this.BindGrid();
}
protected void GridView_RowUpdatingEventHandler(object sender, GridViewUpdateEventArgs e)
{
new Action( async () =>
{
GridView gridView = (GridView)sender;
//get keys.
var entityID = (int)gridView.DataKeys[e.RowIndex].Value;
//find entity
var entity = await this.Find( new object[] { entityID } );
//TODO: edit fields.
//update entity
await this.Edit( entity );
//cancel edit mode.
gridView.EditIndex = -1;
//rebind.
this.BindGrid();
} ).Invoke();
}
protected void GridView_RowDeletingEventHandler(object sender, GridViewDeleteEventArgs e)
{
new Action( async () =>
{
GridView gridView = (GridView)sender;
//get keys.
var entityID = (int)gridView.DataKeys[e.RowIndex].Value;
//find entity.
//find entity.
var entity = await this.Find( new object[] { entityID } );
if (entity != null)
{
//one to many association.
//TODO
//e.g. entity.CustomerType.CustomerTypeID = string.Empty;
//many to one association.
//TODO:
//ICollection<Project> projectList = this.UnitOfWork.GetCustomRepository<CustomerRepository>().GetProjects( entityID );
//foreach (var project in projectList)
//{
// entity.Projects.Remove( project );
//}
//delete.
await this.Delete( entity );
}
//cancel edit mode.
gridView.EditIndex = -1;
//rebind.
this.BindGrid();
} ).Invoke();
}
protected void GridView_SortingEventHandler(object sender, GridViewSortEventArgs e)
{
GridView gridView = (GridView)sender;
if (e.SortExpression == this.SortBy)
{//toggle sort on same.
switch (this.SortDirection)
{
case MWeb.Web.UI.SortDirection.Asc:
this.SortDirection = MWeb.Web.UI.SortDirection.Desc;
break;
case MWeb.Web.UI.SortDirection.Desc:
this.SortDirection = MWeb.Web.UI.SortDirection.Asc;
break;
default:
this.SortDirection = MWeb.Web.UI.SortDirection.Asc;
break;
}
}
else
{//new sort.
this.SortBy = e.SortExpression;
this.SortDirection = MWeb.Web.UI.SortDirection.Asc;
}
//rebind.
this.BindGrid();
}
#endregion
#region Filter Event Handlers
protected void DropDownList_SelectedIndexChangedEventHandler(object sender, System.EventArgs e)
{
DropDownList ddlSender = (DropDownList)sender;
//set filters.
if (sender.Equals(this.ProfileIdKeyFilter))
{
if (this.ProfileIdKeyFilter.IncludeExtraItem)
{
this.ProfileId = (ddlSender.SelectedIndex == 0) ? null : this.ProfileIdKeyFilter.SelectedTypedValue;
}
else
{
this.ProfileId = this.ProfileIdKeyFilter.SelectedTypedValue;
}
}
//reset page.
this.PageNumber = 1;
//TODO: Update pager.
//set grid page.
this.DefaultGridView.PageIndex = this.PageNumber - 1; //fires events.
//rebind.
this.BindGrid();
}
protected void RadioButtonList_SelectedIndexChangedEventHandler(object sender, System.EventArgs e)
{
RadioButtonList rblSender = (RadioButtonList)sender;
//set filters.
//reset page.
this.PageNumber = 1; //current page (e.g. page 2) may not contain filtered results.
//rebind.
this.BindGrid();
}
#endregion
#endregion
}
}
<%@Page Async="true" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Athletes.aspx.cs" Inherits="MWeb.Website.Administration.AthletesPage" %>
<asp:Content ID="ToolBar" ContentPlaceHolderID="ContentToolBarPlaceHolder" runat="server">
<!-- Content Toolbar -->
<div id="ContentToolBar" class="form-actions">
<div class="pull-left">
<button ID="ExportButton" class="btn btn-default" causesvalidation="false" enableviewstate="false" title="Click here to export items." data-loading-text="Exporting..." onserverclick="HtmlButton_ServerClickEventHandler" runat="server"><i class="fa fa-download fa-fw"></i> Export Items</button>
</div>
<div class="pull-right">
<button ID="CreateButton" class="btn btn-success" causesvalidation="false" enableviewstate="false" title="Click here to add new item." data-loading-text="Creating..." onserverclick="HtmlButton_ServerClickEventHandler" runat="server"><i class="fa fa-plus fa-fw"></i> Create New Item <i class="glyphicon glyphicon-chevron-right"></i></button>
</div>
</div>
</asp:Content>
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
<!-- Filter Container (Tabbable) -->
<div id="FilterContainer" class="tabbable">
<!-- Tabs -->
<ul id="FilterTabs" class="nav nav-tabs">
<li id="SearchTab"<% if (this.HasSearchText || (!this.HasSearchText && !this.IsFiltered)){ %> class="active"<% } %>><a href="#SearchPane" data-toggle="tab"><i class="fa fa-search fa-fw"></i> Search</a></li>
<li id="FilterTab"<% if (this.IsFiltered){ %> class="active"<% } %>><a href="#FilterPane" data-toggle="tab"><i class="fa fa-filter fa-fw"></i> Filter By</a></li>
</ul>
<!-- Tab Content -->
<div id="FilterTabContent" class="tab-content">
<div id="SearchPane" class="tab-pane<% if (this.HasSearchText || (!this.HasSearchText && !this.IsFiltered)){ %> active<% } %>">
<div id="EntityListingSearchForm" class="form-horizontal" role="form">
<div class="form-group">
<div class="input-group">
<asp:TextBox ID="SearchTextBox" CssClass="form-control" TextMode="Search" ValidationGroup="search-validation-group" PlaceHolder="Search keywords" runat="server" />
<asp:RequiredFieldValidator ID="SearchTextRequiredFieldValidator" ControlToValidate="SearchTextBox" ValidationGroup="search-validation-group" ErrorMessage="You must provide a search." Display="None" SetFocusOnError="true" runat="server" />
<div class="input-group-btn"><button ID="SearchButton" class="btn btn-default" validationgroup="search-validation-group" enableviewstate="false" title="Click here to search" data-loading-text="Searching..." onserverclick="HtmlButton_ServerClickEventHandler" runat="server">Search</button></div>
</div>
</div>
</div>
<asp:ValidationSummary ID="ValidationSummarySearchText" Enabled="false" Visible="false" ValidationGroup="search-validation-group" CssClass="error" DisplayMode="SingleParagraph" ShowSummary="True" runat="server" />
</div>
<div id="FilterPane" class="tab-pane<% if (this.IsFiltered){ %> active<% } %>">
<!-- DropDown Filters -->
<ul id="DropDownFilters" class="pull-left list-inline">
<li>
<!-- ProfileId -->
<label for="<%= this.ProfileIdKeyFilter.ClientID %>">Profile Id:</label>
<wc:ProfileDropDownList ID="ProfileIdKeyFilter" AutoPostBack="true" CausesValidation="false" CssClass="form-control" IncludeExtraItem="true" ExtraItemPosition="Top" ExtraItemText="-- select item" ExtraItemValue="" OnSelectedIndexChanged="DropDownList_SelectedIndexChangedEventHandler" runat="server" />
</li>
</ul>
<a rel="reload" class="btn btn-default btn-sm pull-right" href="#" title="Click here to reset &amp; reload."data-loading-text="Resetting..." ><i class="glyphicon glyphicon-refresh"></i> Reset</a>
</div>
</div>
</div>
<!-- Filter Message -->
<div id="FilteredMessage" clientidmode="static" class="alert alert-warning fade in" enableviewstate="false" visible="false" runat="server">
<button type="button" class="close" data-dismiss="alert">×</button>
<i class="glyphicon glyphicon-filter"></i> <strong>Filtered Results!</strong> The search results below are filtered. Would you like to <a rel="reload" href="#" title="Click here to reset &amp; reload.">reset view <i class="glyphicon glyphicon-refresh"></i></a>
</div>
<!-- GridView Display -->
<div class="table-responsive">
<asp:GridView
ID="DefaultGridView"
CssClass="grid-view table table-hover table-striped"
AutoGenerateColumns="False"
EnableViewState="True"
AllowPaging="True"
AllowSorting="True"
ShowHeader="True"
ShowFooter="False"
GridLines="None"
ItemType="MWeb.Data.Model.Athlete"
DataKeyNames="ProfileId"
OnRowDataBound="GridView_RowDataBoundEventHandler"
OnPageIndexChanged="GridView_PageIndexChangedEventHandler"
OnRowEditing="GridView_RowEditingEventHandler"
OnRowCancelingEdit="GridView_RowCancelingEditEventHandler"
OnRowUpdating="GridView_RowUpdatingEventHandler"
OnRowDeleting="GridView_RowDeletingEventHandler"
OnSorting="GridView_SortingEventHandler"
Width="100%"
runat="server">
<HeaderStyle CssClass="header-style" />
<RowStyle CssClass="row-style" />
<AlternatingRowStyle CssClass="alternate-row-style" />
<EmptyDataTemplate><div class="empty-template"><h4>Nothing found.</h4><p>No results to display<% if (this.HasSearchText){ %> for search: <em><%= this.SearchText %></em> <a rel="reload" href="#" title="Click here to reset &amp; reload."><i class="glyphicon glyphicon-refresh"></i> reset view<% } %></p><br /><p><a href="modify<%= this.FileName %>" class="btn btn-sm btn-success"><i class="glyphicon glyphicon-plus-sign"></i> create new item <i class="glyphicon glyphicon-chevron-right"></i></a></p></div></EmptyDataTemplate>
<Columns>
<asp:TemplateField
AccessibleHeaderText="Profile Id"
HeaderText="Profile Id"
SortExpression="ProfileId"
ItemStyle-CssClass="item-style-key"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="90px">
<ItemTemplate>
<a href='modifyAthletes.aspx?id=<%#: Item.ProfileId %>'><%#: Item.ProfileId %></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
AccessibleHeaderText="Athlete Type"
HeaderText="Athlete Type"
DataField="AthleteType"
HtmlEncode="False"
DataFormatString="{0:0}"
NullDisplayText="-"
SortExpression="AthleteType"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Athlete Class"
HeaderText="Athlete Class"
DataField="AthleteClass"
HtmlEncode="False"
DataFormatString="{0:0}"
NullDisplayText="-"
SortExpression="AthleteClass"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Height In Centimeters"
HeaderText="Height In Centimeters"
DataField="HeightInCentimeters"
HtmlEncode="False"
DataFormatString="{0:0}"
NullDisplayText="-"
SortExpression="HeightInCentimeters"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Height In Inches"
HeaderText="Height In Inches"
DataField="HeightInInches"
HtmlEncode="False"
DataFormatString="{0:d}"
NullDisplayText="-"
SortExpression="HeightInInches"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Weight In Kilograms"
HeaderText="Weight In Kilograms"
DataField="WeightInKilograms"
HtmlEncode="False"
DataFormatString="{0:0}"
NullDisplayText="-"
SortExpression="WeightInKilograms"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Weight In Pounds"
HeaderText="Weight In Pounds"
DataField="WeightInPounds"
HtmlEncode="False"
DataFormatString="{0:0}"
NullDisplayText="-"
SortExpression="WeightInPounds"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Years In Sport"
HeaderText="Years In Sport"
DataField="YearsInSport"
HtmlEncode="False"
DataFormatString="{0:0}"
NullDisplayText="-"
SortExpression="YearsInSport"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Years As Pro"
HeaderText="Years As Pro"
DataField="YearsAsPro"
HtmlEncode="False"
DataFormatString="{0:0}"
NullDisplayText="-"
SortExpression="YearsAsPro"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:TemplateField
HeaderText="Represent Country Name"
AccessibleHeaderText="Represent Country Name"
SortExpression="RepresentCountryName"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="True"
ItemStyle-Width="250px">
<ItemTemplate>
<a href='modifyAthletes.aspx?id=<%#: Item.ProfileId %>'><%#: Item.RepresentCountryName %></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
AccessibleHeaderText="Represent Country Iso 2 Code"
HeaderText="Represent Country Iso 2 Code"
DataField="RepresentCountryIso2Code"
NullDisplayText="-"
SortExpression="RepresentCountryIso2Code"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Coach Full Name"
HeaderText="Coach Full Name"
DataField="CoachFullName"
NullDisplayText="-"
SortExpression="CoachFullName"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Coach Title"
HeaderText="Coach Title"
DataField="CoachTitle"
NullDisplayText="-"
SortExpression="CoachTitle"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:TemplateField
AccessibleHeaderText="Coach Url"
HeaderText="Coach Url"
ConvertEmptyStringToNull="True"
SortExpression="CoachUrl"
HeaderStyle-HorizontalAlign="Left"
ItemStyle-CssClass="item-style-url"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="150px" >
<ItemTemplate>
<a target="blank" href="<%#: Item.CoachUrl %>"><%#: Item.CoachUrl %></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
AccessibleHeaderText="Agent Full Name"
HeaderText="Agent Full Name"
DataField="AgentFullName"
NullDisplayText="-"
SortExpression="AgentFullName"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Agent Title"
HeaderText="Agent Title"
DataField="AgentTitle"
NullDisplayText="-"
SortExpression="AgentTitle"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:TemplateField
AccessibleHeaderText="Agent Url"
HeaderText="Agent Url"
ConvertEmptyStringToNull="True"
SortExpression="AgentUrl"
HeaderStyle-HorizontalAlign="Left"
ItemStyle-CssClass="item-style-url"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="150px" >
<ItemTemplate>
<a target="blank" href="<%#: Item.AgentUrl %>"><%#: Item.AgentUrl %></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
AccessibleHeaderText="Agency Name"
HeaderText="Agency Name"
DataField="AgencyName"
NullDisplayText="-"
SortExpression="AgencyName"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:TemplateField
AccessibleHeaderText="Agency Url"
HeaderText="Agency Url"
ConvertEmptyStringToNull="True"
SortExpression="AgencyUrl"
HeaderStyle-HorizontalAlign="Left"
ItemStyle-CssClass="item-style-url"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="150px" >
<ItemTemplate>
<a target="blank" href="<%#: Item.AgencyUrl %>"><%#: Item.AgencyUrl %></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
AccessibleHeaderText="Personal Bests"
HeaderText="Personal Bests"
DataField="PersonalBests"
NullDisplayText="-"
SortExpression="PersonalBests"
ItemStyle-HorizontalAlign="Left"
ItemStyle-Wrap="False"
ItemStyle-Width="100px"
ReadOnly="true"
Visible="false" />
<asp:BoundField
AccessibleHeaderText="Order Index"
HeaderText="Order"
DataField="OrderIndex"
HtmlEncode="False"
DataFormatString="{0:0}"
NullDisplayText="-"
SortExpression="OrderIndex"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-CssClass="item-style-orderindex"
ItemStyle-HorizontalAlign="Center"
ItemStyle-Wrap="False"
ItemStyle-Width="40px"
ReadOnly="true" />
<asp:TemplateField
AccessibleHeaderText="Edit"
ItemStyle-CssClass="item-style-edit"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center"
ItemStyle-Width="20px"
ItemStyle-Wrap="false">
<ItemTemplate>
<a class="btn btn-xs btn-default" href='modifyAthletes.aspx?id=<%# Item.ProfileId %>'>Edit</a>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField
AccessibleHeaderText="Delete"
ShowDeleteButton="True"
CausesValidation="false"
ButtonType="Link"
DeleteText="Delete"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-CssClass="item-style-delete"
ItemStyle-HorizontalAlign="Center"
ItemStyle-Width="20px"
ItemStyle-Wrap="false" />
</Columns>
</asp:GridView>
</div>
<div id="DisplayToolBar">
<div class="row">
<div class="col-sm-24">
<nav id="BottomPager"><!-- jquery.bootpage.js --></nav>
</div>
<div class="col-sm-24">
<div id="DataToolBar" class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-primary"><%= this.PageSize %> Per Page</button>
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#" data-page-size="10" onserverclick="PageSizeLink_ServerClickEventHandler" runat="server">10 Per Page</a></li>
<li><a href="#" data-page-size="25" onserverclick="PageSizeLink_ServerClickEventHandler" runat="server">25 Per Page</a></li>
<li><a href="#" data-page-size="50" onserverclick="PageSizeLink_ServerClickEventHandler" runat="server">50 Per Page</a></li>
<li><a href="#" data-page-size="100" onserverclick="PageSizeLink_ServerClickEventHandler" runat="server">100 Per Page</a></li>
<li><a href="#" data-page-size="250" onserverclick="PageSizeLink_ServerClickEventHandler" runat="server">250 Per Page</a></li>
<li class="divider"></li>
<li><a href="#" data-page-size="1000" onserverclick="PageSizeLink_ServerClickEventHandler" runat="server">1000 Per Page</a></li>
</ul>
</div>
<button ID="ResetButton" class="btn btn-default btn-sm" causesvalidation="false" enableviewstate="false" title="Click here to reset." data-loading-text="Resetting..." onserverclick="HtmlButton_ServerClickEventHandler" runat="server"><i class="glyphicon glyphicon-refresh"></i> Reset</button>
</div>
</div>
</div>
</div>
</asp:Content>
<asp:Content ID="PageStyles" ContentPlaceHolderID="PageStylesContentPlaceHolder" runat="server">
<style type="text/css">
</style>
</asp:Content>
<asp:Content ID="PageScripts" ContentPlaceHolderID="PageScriptsContentPlaceHolder" runat="server">
<script src="<%= this.ResolveUrl('~') %>/assets/js/libraries/jquery.bootpag.min.js" type="text/javascript"></script>
<script type="text/javascript">
// <![CDATA[
// IIFE - Immediately Invoked Function Expression
(function (library)
{
library(window.jQuery, window, document);
}(function ($, window, document)
{
// listen for the jQuery ready event on the document
$(function ()
{//dom is ready!
var init = function ()
{
_pageInit();
}();
});
// init
var _pageInit = function ()
{
//pager
_pagerInit();
};
var _pagerInit = function()
{
//code here.
}
}));
// ]]>
</script>
</asp:Content>
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Repository.Pattern.Ef6;
using Repository.Pattern.Ef6.Factories;
using Repository.Pattern.Infrastructure;
using Repository.Pattern.UnitOfWork;
using Repository.Pattern.Repositories;
using MWeb.Web.UI;
using MWeb.Web.UI.Repository;
using MWeb.Data.Model;
using MWeb.Data.Repository;
namespace MWeb.Website.Administration
{
/// <summary>
/// Summary description for _default.
/// </summary>
public partial class ModifyAthletesPage : MWeb.Web.UI.Repository.RepositoryEntityModifierBasePage<Athlete>
{
#region Constructors
/// <summary>
/// Default Constructor.
/// </summary>
public ModifyAthletesPage():
base()
{
//event handlers
this.Init += new System.EventHandler( this.Page_Init );
this.Load += new System.EventHandler( this.Page_Load );
this.PreRender += new System.EventHandler( this.Page_PreRender );
//data context.
var dataContext = new SolariEnergy.Data.Entity.SolariEnergyContext();
//setup custom repository
UnitOfWork unitOfWork = null;
var factories = new Dictionary<Type, Func<dynamic>>
{
{
typeof (AthleteRepository),
() => new AthleteRepository(dataContext, unitOfWork)
}
};
//uow & repositories.
var repositoryProvider = new RepositoryProvider( new RepositoryFactories( factories ) );
unitOfWork = new UnitOfWork( dataContext, repositoryProvider );
var repository = new AthleteRepository( dataContext, unitOfWork );
repositoryProvider.SetRepository<AthleteRepository>(repository);
//members.
this.UnitOfWork = unitOfWork;
this.Repository = repository;
}
#endregion
#region Page Event Handlers
/// <summary>
/// Page Init Event
/// </summary>
private void Page_Init(object sender, System.EventArgs e)
{
}
/// <summary>
/// Page Load Event
/// </summary>
private void Page_Load(object sender, System.EventArgs e)
{
//setup buttons
this.DuplicateButtonLink.Visible = this.HasEntityID;
this.DeleteButton.Visible = this.HasEntityID;
this.SaveAndContinueButton.Visible = !(this.HasEntityID || this.HasReturnUrl);
this.CreateButtonLink.HRef = this.FileName;
if (this.DuplicateButtonLink.Visible)
{
this.DuplicateButtonLink.HRef = string.Format( "{0}?copy={1}", this.FileName, string.Join( ",", this.EntityID ) );
}
//readonly key controls.
if (this.HasEntityID)
{
}
//get count.
var query = this.UnitOfWork.RepositoryAsync<Athlete>().Queryable();
int totalCount = query.Count<Athlete>();
//update page heading
this.PageHeading += "<small>" + totalCount + " record" + ((totalCount == 1) ? string.Empty : "s") + " found.</small><a class=\"btn btn-link\" href=\"" + this.FileName.Remove( 0, "modify".Length ) + "\"><i class=\"glyphicons unshare\"></i><br />Back to Index</a>";
//update entity controls.
if (!Page.IsPostBack)
{
string copyKeys = Request.QueryString["copy"];
if (!string.IsNullOrWhiteSpace( copyKeys ))
{//copy.
new Action( async () =>
{
string[] keys = copyKeys.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
object[] entityID = new object[keys.Length];
entityID[0] = Convert.ToInt32( keys[0] );
var entityItem = await this.Find( entityID );
entityItem.ProfileId += "-COPY";
this.UpdateEntityControls( entityItem );
} ).Invoke();
}
else if (this.HasEntityID)
{//find.
new Action( async () =>
{
if (this.HasEntityID)
{
var entityItem = await this.Find( this.EntityID );
this.UpdateEntityControls( entityItem );
}
} ).Invoke();
}
else
{//new
IQueryable<Athlete> query = this.UnitOfWork.RepositoryAsync<Athlete>().Queryable();
int totalCount = query.Count<Athlete>();
//set orderindex
//this.txtOrderIndex.Text = totalCount.ToString();
}
}
}
/// <summary>
/// Page PreRender Event
/// </summary>
private void Page_PreRender(object sender, System.EventArgs e)
{
}
#endregion
#region Methods
#region UI Methods
/// <summary>
/// Sets up page.
/// </summary>
private void UpdateEntityControls( Athlete entityItem )
{
this.ddlProfileId.SelectedValue = entityItem.ProfileId.ToString();
this.txtAthleteType.Text = entityItem.AthleteType.ToString();
this.txtAthleteClass.Text = entityItem.AthleteClass.ToString();
this.txtHeightInCentimeters.Text = entityItem.HeightInCentimeters.ToString();
this.txtHeightInInches.Text = entityItem.HeightInInches.ToString("0.00");
this.txtWeightInKilograms.Text = entityItem.WeightInKilograms.ToString();
this.txtWeightInPounds.Text = entityItem.WeightInPounds.ToString();
this.txtYearsInSport.Text = entityItem.YearsInSport.ToString();
this.txtYearsAsPro.Text = entityItem.YearsAsPro.ToString();
this.txtRepresentCountryName.Text = entityItem.RepresentCountryName;
this.txtRepresentCountryIso2Code.Text = entityItem.RepresentCountryIso2Code;
this.txtCoachFullName.Text = entityItem.CoachFullName;
this.txtCoachTitle.Text = entityItem.CoachTitle;
this.txtCoachUrl.Text = entityItem.CoachUrl;
this.txtAgentFullName.Text = entityItem.AgentFullName;
this.txtAgentTitle.Text = entityItem.AgentTitle;
this.txtAgentUrl.Text = entityItem.AgentUrl;
this.txtAgencyName.Text = entityItem.AgencyName;
this.txtAgencyUrl.Text = entityItem.AgencyUrl;
this.txtPersonalBests.Text = entityItem.PersonalBests;
this.txtOrderIndex.Text = entityItem.OrderIndex.ToString();
}
#endregion
#region Save Changes
/// <summary>
/// Saves all changes to database.
/// </summary>
/// <returns>the return value from db transaction.</returns>
public void Save()
{
//sanitize key values
int profileId = Convert.ToInt32(this.ddlProfileId.SelectedValue);
//get control values
int athleteType = Convert.ToInt32(this.txtAthleteType.Text);
int athleteClass = Convert.ToInt32(this.txtAthleteClass.Text);
int heightInCentimeters = Convert.ToInt32(this.txtHeightInCentimeters.Text);
double heightInInches = Convert.ToDouble(this.txtHeightInInches.Text);
int weightInKilograms = Convert.ToInt32(this.txtWeightInKilograms.Text);
int weightInPounds = Convert.ToInt32(this.txtWeightInPounds.Text);
int yearsInSport = Convert.ToInt32(this.txtYearsInSport.Text);
int yearsAsPro = Convert.ToInt32(this.txtYearsAsPro.Text);
string representCountryName = this.txtRepresentCountryName.Text;
string representCountryIso2Code = this.txtRepresentCountryIso2Code.Text;//optional
string coachFullName = this.txtCoachFullName.Text;//optional
string coachTitle = this.txtCoachTitle.Text;//optional
string coachUrl = this.txtCoachUrl.Text;//optional
string agentFullName = this.txtAgentFullName.Text;//optional
string agentTitle = this.txtAgentTitle.Text;//optional
string agentUrl = this.txtAgentUrl.Text;//optional
string agencyName = this.txtAgencyName.Text;//optional
string agencyUrl = this.txtAgencyUrl.Text;//optional
string personalBests = this.txtPersonalBests.Text;//optional
int orderIndex = Convert.ToInt32(this.txtOrderIndex.Text);
//save entity
new Action( async () =>
{
if (this.HasEntityID)
{//edit
var entity = await this.Find( this.EntityID );
if (entity != null)
{
entity.ProfileId = profileId;
entity.AthleteType = athleteType;
entity.AthleteClass = athleteClass;
entity.HeightInCentimeters = heightInCentimeters;
entity.HeightInInches = heightInInches;
entity.WeightInKilograms = weightInKilograms;
entity.WeightInPounds = weightInPounds;
entity.YearsInSport = yearsInSport;
entity.YearsAsPro = yearsAsPro;
entity.RepresentCountryName = representCountryName;
entity.RepresentCountryIso2Code = representCountryIso2Code;
entity.CoachFullName = coachFullName;
entity.CoachTitle = coachTitle;
entity.CoachUrl = coachUrl;
entity.AgentFullName = agentFullName;
entity.AgentTitle = agentTitle;
entity.AgentUrl = agentUrl;
entity.AgencyName = agencyName;
entity.AgencyUrl = agencyUrl;
entity.PersonalBests = personalBests;
entity.OrderIndex = orderIndex;
//TODO: associations.
await this.Edit( entity );
}
}
else
{//create
var entity = new Athlete
{
ProfileId = profileId,
AthleteType = athleteType,
AthleteClass = athleteClass,
HeightInCentimeters = heightInCentimeters,
HeightInInches = heightInInches,
WeightInKilograms = weightInKilograms,
WeightInPounds = weightInPounds,
YearsInSport = yearsInSport,
YearsAsPro = yearsAsPro,
RepresentCountryName = representCountryName,
RepresentCountryIso2Code = representCountryIso2Code,
CoachFullName = coachFullName,
CoachTitle = coachTitle,
CoachUrl = coachUrl,
AgentFullName = agentFullName,
AgentTitle = agentTitle,
AgentUrl = agentUrl,
AgencyName = agencyName,
AgencyUrl = agencyUrl,
PersonalBests = personalBests,
OrderIndex = orderIndex
};
//TODO: associations.
await this.Create( entity );
}
} ).Invoke();
}
#endregion
#endregion
#region Event Handlers
#region Html Button Click Event Handlers
/// <summary>
/// Button Server Click Event Handler.
/// </summary>
protected void HtmlButton_ServerClickEventHandler(object sender, System.EventArgs e)
{
//sender button.
HtmlButton btnSender = (HtmlButton)sender;
//default redirect to current page
string redirectUrl = this.FileName.ToLower().Replace("modify", String.Empty);
//hide message
this.lblMessage.Visible = false;
if (sender.Equals(this.SaveButton))
{
Page.Validate("default-validation-group");
if (!Page.IsValid)
return;
//save.
this.Save();
}
else if (sender.Equals(this.SaveAndContinueButton))
{
Page.Validate("default-validation-group");
if (!Page.IsValid)
return;
//save changes
this.Save();
//redirect to new page.
redirectUrl = this.FileName;
}
else if (sender.Equals( this.DeleteButton ))
{
new Action( async () =>
{
if (this.HasEntityID)
{
//find entity.
var entity = await this.Find( this.EntityID );
if (entity != null)
{
//one to many association.
//TODO
//e.g. entity.CustomerType.CustomerTypeID = string.Empty;
//many to one association.
//TODO:
//ICollection<Project> projectList = this.UnitOfWork.GetCustomRepository<CustomerRepository>().GetProjects( this.EntityID );
//foreach (var project in projectList)
//{
// entity.Projects.Remove( project );
//}
//delete.
await this.Delete( entity );
} }
} ).Invoke();
}
else if (sender.Equals( this.CancelButton ))
{
//fall through
}
//return url.
if (this.HasReturnUrl)
{
redirectUrl = this.ReturnUrl;
}
//no validation - redirect immediately.
if (!btnSender.CausesValidation)
{
Response.Redirect(redirectUrl, false);
}
else
{//redirect if valid..
if (Page.IsValid)
{
Response.Redirect(redirectUrl, false);
}
}
}
#endregion
#endregion
}
}
<%@Page Async="true" AutoEventWireup="True" Language="C#" MasterPageFile="~/Site.master" CodeBehind="ModifyAthletes.aspx.cs" Inherits="MWeb.Website.Administration.ModifyAthletesPage" %>
<asp:Content ID="ToolBar" ContentPlaceHolderID="ContentToolBarPlaceHolder" runat="server">
<!-- Content Toolbar -->
<div id="ContentToolBar" class="form-actions">
<div class="pull-left">
<a id="DuplicateButtonLink" class="btn btn-default" href="#" title="Click here to duplicate item." data-loading-text="Duplicating..." runat="server"><i class="glyphicon glyphicon-repeat"></i> Duplicate Item</a>
</div>
<div class="pull-right">
<a id="CreateButtonLink" class="btn btn-success" href="#" title="Click here to create new item." data-loading-text="Creating..." runat="server"><i class="glyphicon glyphicon-plus-sign"></i> Create New Item <i class="glyphicon glyphicon-chevron-right"></i></a>
</div>
</div>
</asp:Content>
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
<!-- Entity Form -->
<div id="EntityForm" role="form">
<!-- Validation & Message Display -->
<asp:ValidationSummary ID="vsValidationSummary" ValidationGroup="default-validation-group" CssClass="validation-summary alert alert-danger alert-dimissable fade in" HeaderText="<button type='button' class='close' data-dismiss='alert'><span aria-hidden='true'>&times;</span><span class='sr-only'>Close</span></button> <h4><i class='glyphicon glyphicon-warning-sign'></i> Oops! Your having problems.</h4>" DisplayMode="BulletList" ShowSummary="True" runat="server" />
<asp:Label ID="lblMessage" CssClass="confirm-display" Visible="false" runat="server" />
<fieldset>
<h3>Athlete Details</h3>
<div class="form-group is-key is-required">
<!-- Profile Id -->
<label class="control-label" for="<%= this.ddlProfileId.ClientID %>">Profile Id:</label>
<div class="input-group">
<wc:ProfileDropDownList ID="ddlProfileId" CssClass="form-control" runat="server" />
<span class="input-group-addon"><button class="btn" onclick="location.href='./modifyProfiles.aspx?ReturnUrl=<%= Server.UrlEncode(Request.Url.PathAndQuery.ToString()) %>';return false;"><i class="glyphicon glyphicon-plus-sign"></i></button></span>
</div>
<asp:RequiredFieldValidator ID="rfvProfileId" ControlToValidate="ddlProfileId" ValidationGroup="default-validation-group" ErrorMessage="Profile Id must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revProfileId" ControlToValidate="ddlProfileId" ValidationGroup="default-validation-group" ErrorMessage="Profile Id must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
<div class="form-group is-required">
<!-- Athlete Type -->
<label class="control-label" for="<%= this.txtAthleteType.ClientID %>">Athlete Type:</label>
<asp:TextBox ID="txtAthleteType" CssClass="form-control text numeric" Text="" TextMode="Number" ToolTip="Please enter the athlete type." Columns="10" MaxLength="10" data-msg-required="Please enter the athlete type." runat="server" />
<asp:RequiredFieldValidator ID="rfvAthleteType" ControlToValidate="txtAthleteType" ValidationGroup="default-validation-group" ErrorMessage="Athlete Type must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revAthleteType" ControlToValidate="txtAthleteType" ValidationGroup="default-validation-group" ErrorMessage="Athlete Type must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
<div class="form-group is-required">
<!-- Athlete Class -->
<label class="control-label" for="<%= this.txtAthleteClass.ClientID %>">Athlete Class:</label>
<asp:TextBox ID="txtAthleteClass" CssClass="form-control text numeric" Text="" TextMode="Number" ToolTip="Please enter the athlete class." Columns="10" MaxLength="10" data-msg-required="Please enter the athlete class." runat="server" />
<asp:RequiredFieldValidator ID="rfvAthleteClass" ControlToValidate="txtAthleteClass" ValidationGroup="default-validation-group" ErrorMessage="Athlete Class must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revAthleteClass" ControlToValidate="txtAthleteClass" ValidationGroup="default-validation-group" ErrorMessage="Athlete Class must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
<div class="form-group is-required">
<!-- Height In Centimeters -->
<label class="control-label" for="<%= this.txtHeightInCentimeters.ClientID %>">Height In Centimeters:</label>
<asp:TextBox ID="txtHeightInCentimeters" CssClass="form-control text numeric" Text="" TextMode="Number" ToolTip="Please enter the height in centimeters." Columns="10" MaxLength="10" data-msg-required="Please enter the height in centimeters." runat="server" />
<asp:RequiredFieldValidator ID="rfvHeightInCentimeters" ControlToValidate="txtHeightInCentimeters" ValidationGroup="default-validation-group" ErrorMessage="Height In Centimeters must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revHeightInCentimeters" ControlToValidate="txtHeightInCentimeters" ValidationGroup="default-validation-group" ErrorMessage="Height In Centimeters must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
<div class="form-group is-required">
<!-- Height In Inches -->
<label class="control-label" for="<%= this.txtHeightInInches.ClientID %>">Height In Inches:</label>
<asp:TextBox ID="txtHeightInInches" CssClass="form-control text decimal" TextMode="SingleLine" PlaceHolder="Height In Inches" ToolTip="Please enter the height in inches." Columns="10" MaxLength="10" data-msg-required="Please enter the height in inches." runat="server" />
<asp:RequiredFieldValidator ID="rfvHeightInInches" ControlToValidate="txtHeightInInches" ValidationGroup="default-validation-group" ErrorMessage="Height In Inches must be provided." Display="None" SetFocusOnError="true" runat="server" />
</div>
<div class="form-group is-required">
<!-- Weight In Kilograms -->
<label class="control-label" for="<%= this.txtWeightInKilograms.ClientID %>">Weight In Kilograms:</label>
<asp:TextBox ID="txtWeightInKilograms" CssClass="form-control text numeric" Text="" TextMode="Number" ToolTip="Please enter the weight in kilograms." Columns="10" MaxLength="10" data-msg-required="Please enter the weight in kilograms." runat="server" />
<asp:RequiredFieldValidator ID="rfvWeightInKilograms" ControlToValidate="txtWeightInKilograms" ValidationGroup="default-validation-group" ErrorMessage="Weight In Kilograms must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revWeightInKilograms" ControlToValidate="txtWeightInKilograms" ValidationGroup="default-validation-group" ErrorMessage="Weight In Kilograms must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
<div class="form-group is-required">
<!-- Weight In Pounds -->
<label class="control-label" for="<%= this.txtWeightInPounds.ClientID %>">Weight In Pounds:</label>
<asp:TextBox ID="txtWeightInPounds" CssClass="form-control text numeric" Text="" TextMode="Number" ToolTip="Please enter the weight in pounds." Columns="10" MaxLength="10" data-msg-required="Please enter the weight in pounds." runat="server" />
<asp:RequiredFieldValidator ID="rfvWeightInPounds" ControlToValidate="txtWeightInPounds" ValidationGroup="default-validation-group" ErrorMessage="Weight In Pounds must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revWeightInPounds" ControlToValidate="txtWeightInPounds" ValidationGroup="default-validation-group" ErrorMessage="Weight In Pounds must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
<div class="form-group is-required">
<!-- Years In Sport -->
<label class="control-label" for="<%= this.txtYearsInSport.ClientID %>">Years In Sport:</label>
<asp:TextBox ID="txtYearsInSport" CssClass="form-control text numeric" Text="" TextMode="Number" ToolTip="Please enter the years in sport." Columns="10" MaxLength="10" data-msg-required="Please enter the years in sport." runat="server" />
<asp:RequiredFieldValidator ID="rfvYearsInSport" ControlToValidate="txtYearsInSport" ValidationGroup="default-validation-group" ErrorMessage="Years In Sport must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revYearsInSport" ControlToValidate="txtYearsInSport" ValidationGroup="default-validation-group" ErrorMessage="Years In Sport must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
<div class="form-group is-required">
<!-- Years As Pro -->
<label class="control-label" for="<%= this.txtYearsAsPro.ClientID %>">Years As Pro:</label>
<asp:TextBox ID="txtYearsAsPro" CssClass="form-control text numeric" Text="" TextMode="Number" ToolTip="Please enter the years as pro." Columns="10" MaxLength="10" data-msg-required="Please enter the years as pro." runat="server" />
<asp:RequiredFieldValidator ID="rfvYearsAsPro" ControlToValidate="txtYearsAsPro" ValidationGroup="default-validation-group" ErrorMessage="Years As Pro must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revYearsAsPro" ControlToValidate="txtYearsAsPro" ValidationGroup="default-validation-group" ErrorMessage="Years As Pro must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
<div class="form-group is-required">
<!-- Represent Country Name -->
<label class="control-label" for="<%= this.txtRepresentCountryName.ClientID %>">Represent Country Name:</label>
<asp:TextBox ID="txtRepresentCountryName" CssClass="form-control text capitalize" TextMode="SingleLine" Text="" PlaceHolder="Represent Country Name" ToolTip="Please enter the represent country name." Columns="50" MaxLength="50" data-msg-required="Please enter the represent country name." runat="server" />
<asp:RequiredFieldValidator ID="rfvRepresentCountryName" ControlToValidate="txtRepresentCountryName" ValidationGroup="default-validation-group" ErrorMessage="Represent Country Name must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator ID="revRepresentCountryName" ControlToValidate="txtRepresentCountryName" ValidationGroup="default-validation-group" ErrorMessage="Represent Country Name must consist of alphabetical characters (and length less than 50)." Display="None"
ValidationExpression="[a-zA-Z0-9()_'&.\s]{1,50}$" SetFocusOnError="true" runat="server" />
</div>
<div class="form-group">
<!-- Represent Country Iso 2 Code -->
<label class="control-label" for="<%= this.txtRepresentCountryIso2Code.ClientID %>">Represent Country Iso 2 Code <small>(optional)</small>:</label>
<asp:TextBox ID="txtRepresentCountryIso2Code" CssClass="form-control text" TextMode="SingleLine" Text="" PlaceHolder="Represent Country Iso 2 Code" ToolTip="Please enter the represent country iso 2 code." Columns="3" MaxLength="3" runat="server" />
</div>
<div class="form-group">
<!-- Coach Full Name -->
<label class="control-label" for="<%= this.txtCoachFullName.ClientID %>">Coach Full Name <small>(optional)</small>:</label>
<asp:TextBox ID="txtCoachFullName" CssClass="form-control text capitalize" TextMode="SingleLine" Text="" PlaceHolder="Coach Full Name" ToolTip="Please enter the coach full name." Columns="100" MaxLength="100" runat="server" />
<asp:RegularExpressionValidator ID="revCoachFullName" ControlToValidate="txtCoachFullName" ValidationGroup="default-validation-group" ErrorMessage="Coach Full Name must consist of alphabetical characters (and length less than 100)." Display="None"
ValidationExpression="[a-zA-Z0-9()_'&.\s]{1,100}$" SetFocusOnError="true" runat="server" />
</div>
<div class="form-group">
<!-- Coach Title -->
<label class="control-label" for="<%= this.txtCoachTitle.ClientID %>">Coach Title <small>(optional)</small>:</label>
<asp:TextBox ID="txtCoachTitle" CssClass="form-control text capitalize" TextMode="SingleLine" Text="" PlaceHolder="Coach Title" ToolTip="Please enter the coach title." Columns="100" MaxLength="100" runat="server" />
<asp:RegularExpressionValidator ID="revCoachTitle" ControlToValidate="txtCoachTitle" ValidationGroup="default-validation-group" ErrorMessage="Coach Title must consist of alphabetical characters (and length less than 100)." Display="None"
ValidationExpression=".{1,100}" SetFocusOnError="true" runat="server" />
</div>
<div class="form-group">
<!-- Coach Url -->
<label class="control-label" for="<%= this.txtCoachUrl.ClientID %>">Coach Url <small>(optional)</small>:</label>
<asp:TextBox ID="txtCoachUrl" CssClass="form-control text url" TextMode="Url" Text="" PlaceHolder="Coach Url" ToolTip="Please enter the coach url." Columns="100" MaxLength="100" runat="server" />
</div>
<div class="form-group">
<!-- Agent Full Name -->
<label class="control-label" for="<%= this.txtAgentFullName.ClientID %>">Agent Full Name <small>(optional)</small>:</label>
<asp:TextBox ID="txtAgentFullName" CssClass="form-control text capitalize" TextMode="SingleLine" Text="" PlaceHolder="Agent Full Name" ToolTip="Please enter the agent full name." Columns="100" MaxLength="100" runat="server" />
<asp:RegularExpressionValidator ID="revAgentFullName" ControlToValidate="txtAgentFullName" ValidationGroup="default-validation-group" ErrorMessage="Agent Full Name must consist of alphabetical characters (and length less than 100)." Display="None"
ValidationExpression="[a-zA-Z0-9()_'&.\s]{1,100}$" SetFocusOnError="true" runat="server" />
</div>
<div class="form-group">
<!-- Agent Title -->
<label class="control-label" for="<%= this.txtAgentTitle.ClientID %>">Agent Title <small>(optional)</small>:</label>
<asp:TextBox ID="txtAgentTitle" CssClass="form-control text capitalize" TextMode="SingleLine" Text="" PlaceHolder="Agent Title" ToolTip="Please enter the agent title." Columns="100" MaxLength="100" runat="server" />
<asp:RegularExpressionValidator ID="revAgentTitle" ControlToValidate="txtAgentTitle" ValidationGroup="default-validation-group" ErrorMessage="Agent Title must consist of alphabetical characters (and length less than 100)." Display="None"
ValidationExpression=".{1,100}" SetFocusOnError="true" runat="server" />
</div>
<div class="form-group">
<!-- Agent Url -->
<label class="control-label" for="<%= this.txtAgentUrl.ClientID %>">Agent Url <small>(optional)</small>:</label>
<asp:TextBox ID="txtAgentUrl" CssClass="form-control text url" TextMode="Url" Text="" PlaceHolder="Agent Url" ToolTip="Please enter the agent url." Columns="100" MaxLength="100" runat="server" />
</div>
<div class="form-group">
<!-- Agency Name -->
<label class="control-label" for="<%= this.txtAgencyName.ClientID %>">Agency Name <small>(optional)</small>:</label>
<asp:TextBox ID="txtAgencyName" CssClass="form-control text capitalize" TextMode="SingleLine" Text="" PlaceHolder="Agency Name" ToolTip="Please enter the agency name." Columns="100" MaxLength="100" runat="server" />
<asp:RegularExpressionValidator ID="revAgencyName" ControlToValidate="txtAgencyName" ValidationGroup="default-validation-group" ErrorMessage="Agency Name must consist of alphabetical characters (and length less than 100)." Display="None"
ValidationExpression="[a-zA-Z0-9()_'&.\s]{1,100}$" SetFocusOnError="true" runat="server" />
</div>
<div class="form-group">
<!-- Agency Url -->
<label class="control-label" for="<%= this.txtAgencyUrl.ClientID %>">Agency Url <small>(optional)</small>:</label>
<asp:TextBox ID="txtAgencyUrl" CssClass="form-control text url" TextMode="Url" Text="" PlaceHolder="Agency Url" ToolTip="Please enter the agency url." Columns="100" MaxLength="100" runat="server" />
</div>
<div class="form-group">
<!-- Personal Bests -->
<label class="control-label" for="<%= this.txtPersonalBests.ClientID %>">Personal Bests <small>(optional)</small>:</label>
<asp:TextBox ID="txtPersonalBests" CssClass="form-control text" TextMode="SingleLine" Text="" PlaceHolder="Personal Bests" ToolTip="Please enter the personal bests." Columns="100" MaxLength="100" runat="server" />
</div>
<div class="form-group is-required">
<!-- Order Index -->
<label class="control-label" for="<%= this.txtOrderIndex.ClientID %>">Order Index:</label>
<asp:TextBox ID="txtOrderIndex" CssClass="form-control text numeric" Text="" TextMode="Number" ToolTip="Please enter the order index." Columns="10" MaxLength="10" data-msg-required="Please enter the order index." runat="server" />
<asp:RequiredFieldValidator ID="rfvOrderIndex" ControlToValidate="txtOrderIndex" ValidationGroup="default-validation-group" ErrorMessage="Order Index must be provided." Display="None" SetFocusOnError="true" runat="server" />
<asp:RegularExpressionValidator Enabled="false" ID="revOrderIndex" ControlToValidate="txtOrderIndex" ValidationGroup="default-validation-group" ErrorMessage="Order Index must be positive or zero integer value!" Display="None"
ValidationExpression="^\d+$" SetFocusOnError="true" runat="server" />
<!-- "^-?\d+$" - postive or negative integer -->
<!-- "^\d+$" - positive or zero integer -->
<!-- "^\d*[1-9]\d*$" - positive integer -->
</div>
</fieldset>
<!-- Buttons -->
<fieldset id="FormActionsToolBar" class="form-actions">
<div class="pull-left">
<button ID="DeleteButton" class="btn btn-danger" causesvalidation="false" enableviewstate="false" title="Click here to delete item." data-loading-text="Deleting..." onserverclick="HtmlButton_ServerClickEventHandler" runat="server"><i class="fa fa-trash fa-fw"></i> Delete</button>
</div>
<div class="pull-right">
<button ID="CancelButton" class="btn btn-default" causesvalidation="false" enableviewstate="false" title="Click here to cancel." data-loading-text="Cancelling..." onserverclick="HtmlButton_ServerClickEventHandler" runat="server"><i class="fa fa-ban fa-fw"></i> Cancel</button>
<button ID="SaveButton" class="btn btn-primary" enableviewstate="false" validationgroup="default-validation-group" title="Click here to save changes." data-loading-text="Saving..." onserverclick="HtmlButton_ServerClickEventHandler" runat="server"><i class="fa fa-save fa-fw"></i> Save</button>
<button ID="SaveAndContinueButton" class="btn btn-primary" enableviewstate="false" validationgroup="default-validation-group" title="Click here to save changes and add another item." data-loading-text="Saving &amp; Continue..." onserverclick="HtmlButton_ServerClickEventHandler" runat="server"><i class="fa fa-save fa-fw"></i> Save &amp; Continue <i class="fa fa-chevron-right fa-fw"></i></button>
</div>
</fieldset>
</div>
<!-- //Data Item Form -->
</asp:Content>
<asp:Content ID="PageStyles" ContentPlaceHolderID="PageStylesContentPlaceHolder" runat="server">
<style type="text/css">
</style>
</asp:Content>
<asp:Content ID="PageScripts" ContentPlaceHolderID="PageScriptsContentPlaceHolder" runat="server">
<script type="text/javascript">
// <![CDATA[
// IIFE - Immediately Invoked Function Expression
(function (library)
{
library(window.jQuery, window, document);
}(function ($, window, document)
{
// listen for the jQuery ready event on the document
$(function ()
{//dom is ready!
var init = function ()
{
_pageInit();
}();
});
// init
var _pageInit = function ()
{
$("input.numeric").TouchSpin({initialValue: 0})
};
}));
// ]]>
</script>
</asp:Content>
--region Drop Existing Procedures
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectAthlete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectAthlete]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectAthleteUsingOutParameters]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectAthleteUsingOutParameters]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectAllAthletes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectAllAthletes]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectAthletesByForeignKey]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectAthletesByForeignKey]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectAthletesBy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectAthletesBy]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectSearchAllAthletes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectSearchAllAthletes]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectSearchAthletesByForeignKey]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectSearchAthletesByForeignKey]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectSearchAthletesBy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectSearchAthletesBy]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectAthletesUsingRowCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectAthletesUsingRowCount]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectAthletesByForeignKeyUsingRowCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectAthletesByForeignKeyUsingRowCount]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectAthletesByUsingRowCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectAthletesByUsingRowCount]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectSearchAthletesUsingRowCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectSearchAthletesUsingRowCount]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectSearchAthletesByForeignKeyUsingRowCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectSearchAthletesByForeignKeyUsingRowCount]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectSearchAthletesByUsingRowCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectSearchAthletesByUsingRowCount]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectPagedAthletes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectPagedAthletes]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectPagedAthletesByForeignKey]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectPagedAthletesByForeignKey]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectPagedAthletesBy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectPagedAthletesBy]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectPagedAthleteSearch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectPagedAthleteSearch]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectPagedAthleteSearchByForeignKey]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectPagedAthleteSearchByForeignKey]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectPagedAthleteSearchBy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectPagedAthleteSearchBy]
--endregion
GO
--region [dbo].[SelectAthlete]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[SelectAthlete]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SelectAthlete]
-- primary key(s)
@ProfileId int,
@IncludeItemCount bit = 0,
@ItemCount bigint = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by pk
* ------------------------------------------------------------- */
SELECT
[dbo].[Athlete].[ProfileId], /* pk */
[dbo].[Profile].[ProfileTitle] AS [ProfileId_Name], /* fk name column */
[dbo].[Athlete].[AthleteType],
[dbo].[Athlete].[AthleteClass],
[dbo].[Athlete].[HeightInCentimeters],
[dbo].[Athlete].[HeightInInches],
[dbo].[Athlete].[WeightInKilograms],
[dbo].[Athlete].[WeightInPounds],
[dbo].[Athlete].[YearsInSport],
[dbo].[Athlete].[YearsAsPro],
[dbo].[Athlete].[RepresentCountryName],
[dbo].[Athlete].[RepresentCountryIso2Code],
[dbo].[Athlete].[CoachFullName],
[dbo].[Athlete].[CoachTitle],
[dbo].[Athlete].[CoachUrl],
[dbo].[Athlete].[AgentFullName],
[dbo].[Athlete].[AgentTitle],
[dbo].[Athlete].[AgentUrl],
[dbo].[Athlete].[AgencyName],
[dbo].[Athlete].[AgencyUrl],
[dbo].[Athlete].[PersonalBests],
[dbo].[Athlete].[OrderIndex]
FROM
[dbo].[Athlete]
INNER JOIN [dbo].[Profile] ON [dbo].[Athlete].[ProfileId] = [dbo].[Profile].[ProfileId]
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAthlete]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[SelectAthlete]''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
DECLARE @ReturnValue int
EXEC @ReturnValue = [dbo].[SelectCountAllAthletes] @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAthlete]'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[SelectAthleteUsingOutParameters]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[SelectAthleteUsingOutParameters]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SelectAthleteUsingOutParameters]
-- primary key(s)
@ProfileId int,
-- output parameters
@AthleteType int OUTPUT,
@AthleteClass int OUTPUT,
@HeightInCentimeters int OUTPUT,
@HeightInInches float OUTPUT,
@WeightInKilograms int OUTPUT,
@WeightInPounds int OUTPUT,
@YearsInSport int OUTPUT,
@YearsAsPro int OUTPUT,
@RepresentCountryName nvarchar(50) OUTPUT,
@RepresentCountryIso2Code nvarchar(3) OUTPUT,
@CoachFullName nvarchar(100) OUTPUT,
@CoachTitle nvarchar(100) OUTPUT,
@CoachUrl nvarchar(100) OUTPUT,
@AgentFullName nvarchar(100) OUTPUT,
@AgentTitle nvarchar(100) OUTPUT,
@AgentUrl nvarchar(100) OUTPUT,
@AgencyName nvarchar(100) OUTPUT,
@AgencyUrl nvarchar(100) OUTPUT,
@PersonalBests nvarchar(100) OUTPUT,
@OrderIndex int OUTPUT,
@IncludeItemCount bit = 0,
@ItemCount bigint = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by key - set output params.
* ------------------------------------------------------------- */
SELECT
@AthleteType = [dbo].[Athlete].[AthleteType],
@AthleteClass = [dbo].[Athlete].[AthleteClass],
@HeightInCentimeters = [dbo].[Athlete].[HeightInCentimeters],
@HeightInInches = [dbo].[Athlete].[HeightInInches],
@WeightInKilograms = [dbo].[Athlete].[WeightInKilograms],
@WeightInPounds = [dbo].[Athlete].[WeightInPounds],
@YearsInSport = [dbo].[Athlete].[YearsInSport],
@YearsAsPro = [dbo].[Athlete].[YearsAsPro],
@RepresentCountryName = [dbo].[Athlete].[RepresentCountryName],
@RepresentCountryIso2Code = [dbo].[Athlete].[RepresentCountryIso2Code],
@CoachFullName = [dbo].[Athlete].[CoachFullName],
@CoachTitle = [dbo].[Athlete].[CoachTitle],
@CoachUrl = [dbo].[Athlete].[CoachUrl],
@AgentFullName = [dbo].[Athlete].[AgentFullName],
@AgentTitle = [dbo].[Athlete].[AgentTitle],
@AgentUrl = [dbo].[Athlete].[AgentUrl],
@AgencyName = [dbo].[Athlete].[AgencyName],
@AgencyUrl = [dbo].[Athlete].[AgencyUrl],
@PersonalBests = [dbo].[Athlete].[PersonalBests],
@OrderIndex = [dbo].[Athlete].[OrderIndex]
FROM
[dbo].[Athlete]
INNER JOIN [dbo].[Profile] ON [dbo].[Athlete].[ProfileId] = [dbo].[Profile].[ProfileId]
WHERE
[dbo].[Athlete].[ProfileId] = @ProfileId
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAthleteUsingOutParameters]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[SelectAthleteUsingOutParameters]''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
DECLARE @ReturnValue int
EXEC @ReturnValue = [dbo].[SelectCountAllAthletes] @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAthleteUsingOutParameters]'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[SelectAllAthletes]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[SelectAllAthletes]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SelectAllAthletes]
@SortBy varchar(50) = 'OrderIndex',
@SortDirection varchar(4) = 'ASC',
@IncludeItemCount bit = 0,
@ItemCount bigint = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select All
* ------------------------------------------------------------- */
SELECT
[dbo].[Athlete].[ProfileId], /* pk */
[dbo].[Profile].[ProfileTitle] AS [ProfileId_Name], /* fk name column */
[dbo].[Athlete].[AthleteType],
[dbo].[Athlete].[AthleteClass],
[dbo].[Athlete].[HeightInCentimeters],
[dbo].[Athlete].[HeightInInches],
[dbo].[Athlete].[WeightInKilograms],
[dbo].[Athlete].[WeightInPounds],
[dbo].[Athlete].[YearsInSport],
[dbo].[Athlete].[YearsAsPro],
[dbo].[Athlete].[RepresentCountryName],
[dbo].[Athlete].[RepresentCountryIso2Code],
[dbo].[Athlete].[CoachFullName],
[dbo].[Athlete].[CoachTitle],
[dbo].[Athlete].[CoachUrl],
[dbo].[Athlete].[AgentFullName],
[dbo].[Athlete].[AgentTitle],
[dbo].[Athlete].[AgentUrl],
[dbo].[Athlete].[AgencyName],
[dbo].[Athlete].[AgencyUrl],
[dbo].[Athlete].[PersonalBests],
[dbo].[Athlete].[OrderIndex]
FROM
[dbo].[Athlete]
INNER JOIN [dbo].[Profile] ON [dbo].[Athlete].[ProfileId] = [dbo].[Profile].[ProfileId]
ORDER BY
-- asc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[ProfileId] END ASC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Profile].[ProfileTitle] END ASC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteType] END ASC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteClass] END ASC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[HeightInCentimeters] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInKilograms] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInPounds] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsInSport] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsAsPro] END ASC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[OrderIndex] END ASC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[CoachTitle] END ASC,
-- desc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[ProfileId] END DESC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Profile].[ProfileTitle] END DESC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteType] END DESC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteClass] END DESC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[HeightInCentimeters] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInKilograms] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInPounds] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsInSport] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsAsPro] END DESC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[OrderIndex] END DESC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[CoachTitle] END DESC
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAllAthletes]''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
DECLARE @ReturnValue int
EXEC @ReturnValue = [dbo].[SelectCountAllAthletes] @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAllAthletes]'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[SelectAthletesByForeignKey]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[SelectAthletesByForeignKey]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SelectAthletesByForeignKey]
-- foreign key(s)
@ProfileId int,
-- sort expressions
@SortBy varchar(50) = 'OrderIndex',
@SortDirection varchar(4) = 'ASC',
-- item count
@IncludeItemCount bit = 0,
@ItemCount bigint = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by fk
* ------------------------------------------------------------- */
SELECT
[dbo].[Athlete].[ProfileId], /* pk */
[dbo].[Profile].[ProfileTitle] AS [ProfileId_Name], /* fk name column */
[dbo].[Athlete].[AthleteType],
[dbo].[Athlete].[AthleteClass],
[dbo].[Athlete].[HeightInCentimeters],
[dbo].[Athlete].[HeightInInches],
[dbo].[Athlete].[WeightInKilograms],
[dbo].[Athlete].[WeightInPounds],
[dbo].[Athlete].[YearsInSport],
[dbo].[Athlete].[YearsAsPro],
[dbo].[Athlete].[RepresentCountryName],
[dbo].[Athlete].[RepresentCountryIso2Code],
[dbo].[Athlete].[CoachFullName],
[dbo].[Athlete].[CoachTitle],
[dbo].[Athlete].[CoachUrl],
[dbo].[Athlete].[AgentFullName],
[dbo].[Athlete].[AgentTitle],
[dbo].[Athlete].[AgentUrl],
[dbo].[Athlete].[AgencyName],
[dbo].[Athlete].[AgencyUrl],
[dbo].[Athlete].[PersonalBests],
[dbo].[Athlete].[OrderIndex]
FROM
[dbo].[Athlete]
INNER JOIN [dbo].[Profile] ON [dbo].[Athlete].[ProfileId] = [dbo].[Profile].[ProfileId]
WHERE
(@ProfileId IS NULL OR [dbo].[Athlete].[ProfileId] = @ProfileId)
ORDER BY
-- asc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[ProfileId] END ASC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Profile].[ProfileTitle] END ASC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteType] END ASC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteClass] END ASC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[HeightInCentimeters] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInKilograms] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInPounds] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsInSport] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsAsPro] END ASC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[OrderIndex] END ASC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[CoachTitle] END ASC,
-- desc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[ProfileId] END DESC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Profile].[ProfileTitle] END DESC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteType] END DESC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteClass] END DESC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[HeightInCentimeters] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInKilograms] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInPounds] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsInSport] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsAsPro] END DESC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[OrderIndex] END DESC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[CoachTitle] END DESC
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAthletesByForeignKey]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
--IF @RowsAffected <> 1
--BEGIN
-- RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[SelectAthletesByForeignKey]''', 10, 1)
-- RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
--END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
DECLARE @ReturnValue int
EXEC @ReturnValue = [dbo].[SelectCountAllAthletes] @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAthletesByForeignKey]'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[SelectAthletesBy]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[SelectAthletesBy]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SelectAthletesBy]
-- foreign key, index and bit columns
@ProfileId int,
-- sort expressions
@SortBy varchar(50) = 'OrderIndex',
@SortDirection varchar(4) = 'ASC',
-- item count
@IncludeItemCount bit = 0,
@ItemCount bigint = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by keys, bits
* ------------------------------------------------------------- */
SELECT
[dbo].[Athlete].[ProfileId], /* pk */
[dbo].[Profile].[ProfileTitle] AS [ProfileId_Name], /* fk name column */
[dbo].[Athlete].[AthleteType],
[dbo].[Athlete].[AthleteClass],
[dbo].[Athlete].[HeightInCentimeters],
[dbo].[Athlete].[HeightInInches],
[dbo].[Athlete].[WeightInKilograms],
[dbo].[Athlete].[WeightInPounds],
[dbo].[Athlete].[YearsInSport],
[dbo].[Athlete].[YearsAsPro],
[dbo].[Athlete].[RepresentCountryName],
[dbo].[Athlete].[RepresentCountryIso2Code],
[dbo].[Athlete].[CoachFullName],
[dbo].[Athlete].[CoachTitle],
[dbo].[Athlete].[CoachUrl],
[dbo].[Athlete].[AgentFullName],
[dbo].[Athlete].[AgentTitle],
[dbo].[Athlete].[AgentUrl],
[dbo].[Athlete].[AgencyName],
[dbo].[Athlete].[AgencyUrl],
[dbo].[Athlete].[PersonalBests],
[dbo].[Athlete].[OrderIndex]
FROM
[dbo].[Athlete]
INNER JOIN [dbo].[Profile] ON [dbo].[Athlete].[ProfileId] = [dbo].[Profile].[ProfileId]
WHERE
(@ProfileId IS NULL OR [dbo].[Athlete].[ProfileId] = @ProfileId)
ORDER BY
-- asc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[ProfileId] END ASC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Profile].[ProfileTitle] END ASC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteType] END ASC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteClass] END ASC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[HeightInCentimeters] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInKilograms] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInPounds] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsInSport] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsAsPro] END ASC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[OrderIndex] END ASC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[CoachTitle] END ASC,
-- desc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[ProfileId] END DESC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Profile].[ProfileTitle] END DESC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteType] END DESC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteClass] END DESC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[HeightInCentimeters] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInKilograms] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInPounds] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsInSport] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsAsPro] END DESC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[OrderIndex] END DESC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[CoachTitle] END DESC
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAthletesBy]''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
DECLARE @ReturnValue int
EXEC @ReturnValue = [dbo].[SelectCountAllAthletes] @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectAthletesBy]'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[SelectSearchAllAthletes]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[SelectSearchAllAthletes]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SelectSearchAllAthletes]
-- search text
@SearchText varchar(50) ,
@SortBy varchar(50) = 'OrderIndex',
@SortDirection varchar(4) = 'ASC',
@IncludeItemCount bit = 0,
@ItemCount bigint = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select Search All
* ------------------------------------------------------------- */
SELECT
[dbo].[Athlete].[ProfileId], /* pk */
[dbo].[Profile].[ProfileTitle] AS [ProfileId_Name], /* fk name column */
[dbo].[Athlete].[AthleteType],
[dbo].[Athlete].[AthleteClass],
[dbo].[Athlete].[HeightInCentimeters],
[dbo].[Athlete].[HeightInInches],
[dbo].[Athlete].[WeightInKilograms],
[dbo].[Athlete].[WeightInPounds],
[dbo].[Athlete].[YearsInSport],
[dbo].[Athlete].[YearsAsPro],
[dbo].[Athlete].[RepresentCountryName],
[dbo].[Athlete].[RepresentCountryIso2Code],
[dbo].[Athlete].[CoachFullName],
[dbo].[Athlete].[CoachTitle],
[dbo].[Athlete].[CoachUrl],
[dbo].[Athlete].[AgentFullName],
[dbo].[Athlete].[AgentTitle],
[dbo].[Athlete].[AgentUrl],
[dbo].[Athlete].[AgencyName],
[dbo].[Athlete].[AgencyUrl],
[dbo].[Athlete].[PersonalBests],
[dbo].[Athlete].[OrderIndex]
FROM
[dbo].[Athlete]
INNER JOIN [dbo].[Profile] ON [dbo].[Athlete].[ProfileId] = [dbo].[Profile].[ProfileId]
WHERE
[dbo].[Athlete].[RepresentCountryName] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[RepresentCountryIso2Code] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[CoachFullName] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[CoachTitle] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[CoachUrl] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgentFullName] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgentTitle] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgentUrl] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgencyName] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgencyUrl] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[PersonalBests] LIKE '%' + @SearchText + '%'
ORDER BY
-- asc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[ProfileId] END ASC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Profile].[ProfileTitle] END ASC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteType] END ASC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteClass] END ASC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[HeightInCentimeters] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInKilograms] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInPounds] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsInSport] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsAsPro] END ASC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[OrderIndex] END ASC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[CoachTitle] END ASC,
-- desc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[ProfileId] END DESC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Profile].[ProfileTitle] END DESC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteType] END DESC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteClass] END DESC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[HeightInCentimeters] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInKilograms] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInPounds] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsInSport] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsAsPro] END DESC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[OrderIndex] END DESC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[CoachTitle] END DESC
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectSearchAllAthletes]''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
DECLARE @ReturnValue int
EXEC @ReturnValue = [dbo].[SelectCountAllAthletes] @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectSearchAllAthletes]'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
--region [dbo].[SelectSearchAthletesByForeignKey]
------------------------------------------------------------------------------------------------------------------------
-- Procedure Name: [dbo].[SelectSearchAthletesByForeignKey]
-- Date Generated: Wednesday, 9 May 2018
-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au
-- Company: MWeb Solutions Pty Ltd
-- Software: CodeSmith v6.0.0.0
-- Template: StoredProcedures.cst
--------- --------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SelectSearchAthletesByForeignKey]
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
@ProfileId int,
-- sort expressions
@SortBy varchar(50) = 'OrderIndex',
@SortDirection varchar(4) = 'ASC',
-- item count
@IncludeItemCount bit = 0,
@ItemCount bigint = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select Search by fk
* ------------------------------------------------------------- */
SELECT
[dbo].[Athlete].[ProfileId], /* pk */
[dbo].[Profile].[ProfileTitle] AS [ProfileId_Name], /* fk name column */
[dbo].[Athlete].[AthleteType],
[dbo].[Athlete].[AthleteClass],
[dbo].[Athlete].[HeightInCentimeters],
[dbo].[Athlete].[HeightInInches],
[dbo].[Athlete].[WeightInKilograms],
[dbo].[Athlete].[WeightInPounds],
[dbo].[Athlete].[YearsInSport],
[dbo].[Athlete].[YearsAsPro],
[dbo].[Athlete].[RepresentCountryName],
[dbo].[Athlete].[RepresentCountryIso2Code],
[dbo].[Athlete].[CoachFullName],
[dbo].[Athlete].[CoachTitle],
[dbo].[Athlete].[CoachUrl],
[dbo].[Athlete].[AgentFullName],
[dbo].[Athlete].[AgentTitle],
[dbo].[Athlete].[AgentUrl],
[dbo].[Athlete].[AgencyName],
[dbo].[Athlete].[AgencyUrl],
[dbo].[Athlete].[PersonalBests],
[dbo].[Athlete].[OrderIndex]
FROM
[dbo].[Athlete]
INNER JOIN [dbo].[Profile] ON [dbo].[Athlete].[ProfileId] = [dbo].[Profile].[ProfileId]
WHERE
(@ProfileId IS NULL OR [dbo].[Athlete].[ProfileId] = @ProfileId)
AND
(
[dbo].[Athlete].[RepresentCountryName] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[RepresentCountryIso2Code] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[CoachFullName] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[CoachTitle] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[CoachUrl] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgentFullName] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgentTitle] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgentUrl] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgencyName] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[AgencyUrl] LIKE '%' + @SearchText + '%' OR
[dbo].[Athlete].[PersonalBests] LIKE '%' + @SearchText + '%'
)
ORDER BY
-- asc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[ProfileId] END ASC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Profile].[ProfileTitle] END ASC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteType] END ASC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[AthleteClass] END ASC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[HeightInCentimeters] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInKilograms] END ASC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[WeightInPounds] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsInSport] END ASC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[YearsAsPro] END ASC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[OrderIndex] END ASC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'ASC' THEN
[dbo].[Athlete].[CoachTitle] END ASC,
-- desc
CASE WHEN LOWER(@SortBy) = 'profileid' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[ProfileId] END DESC,
CASE WHEN LOWER(@SortBy) = 'profileid_name' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Profile].[ProfileTitle] END DESC,
CASE WHEN LOWER(@SortBy) = 'athletetype' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteType] END DESC,
CASE WHEN LOWER(@SortBy) = 'athleteclass' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[AthleteClass] END DESC,
CASE WHEN LOWER(@SortBy) = 'heightincentimeters' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[HeightInCentimeters] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinkilograms' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInKilograms] END DESC,
CASE WHEN LOWER(@SortBy) = 'weightinpounds' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[WeightInPounds] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsinsport' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsInSport] END DESC,
CASE WHEN LOWER(@SortBy) = 'yearsaspro' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[YearsAsPro] END DESC,
CASE WHEN LOWER(@SortBy) = 'orderindex' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[OrderIndex] END DESC,
CASE WHEN LOWER(@SortBy) = 'coachtitle' AND UPPER(@SortDirection) = 'DESC' THEN
[dbo].[Athlete].[CoachTitle] END DESC
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectSearchAthletesByForeignKey]''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
--IF @RowsAffected <> 1
--BEGIN
-- RAISERROR('Unexpected number of rows affected by stored procedure ''[dbo].[SelectSearchAthletesByForeignKey]''', 10, 1)
-- RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
--END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
DECLARE @ReturnValue int
EXEC @ReturnValue = [dbo].[SelectCountAllAthletes] @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''[dbo].[SelectSearchAthletesByForeignKey]'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
--endregion
GO
<%------------------------------------------------------------------------------------------
* Developer: Stephen McCormack stephenm@mwebsolutions.com.au
* Company: MWeb Solutions Pty Ltd http://www.mwebsolutions.com.au
* Description:
*
* This template will generate standard CRUD stored procedures for a given
* database tables.
*
*
* TODO:
* 4. Place IF NOT EXISTS statement on all applicable procedures
* 6. Determine and RETURN NOT FOUND in all statements
* 8. Mapping Tables - create extra procedures for mapping tables where
------------------------------------------------------------------------------------------%>
<%@ CodeTemplate Debug="True" Language="C#" Inherits="CodeSmith.BaseTemplates.SqlCodeTemplate" TargetLanguage="T-SQL"
Description="Generates standard CRUD procedures based on a database table schema." %>
<%-- Context --%>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="01. Context"
Description="Table that the stored procedures should be based on." %>
<%-- Options --%>
<%@ Property Name="IsolationLevel" Type="TransactionIsolationLevelEnum" Default="ReadCommitted" Category="02. Options"
Description="Isolation level to use in the generated procedures." %>
<%@ Property Name="IncludeDropStatements" Type="System.Boolean" Default="True" Category="02. Options"
Description="If true drop statements will be generated to drop existing stored procedures." %>
<%@ Property Name="ProcedurePrefix" Type="System.String" Default="" Optional="True" Category="02. Options"
Description="Prefix to use for all generated procedure names." %>
<%@ Property Name="TablePrefix" Type="System.String" Default="" Optional="True" Category="02. Options"
Description="If this prefix is found at the start of a table name, it will be stripped off." %>
<%@ Property Name="NewColumnPrefix" Type="System.String" Default="New" Optional="True" Category="02. Options"
Description="If this prefix is found, it will be used for any new update columns (i.e. where repeated columns are found in the identifier and update columns)." %>
<%@ Property Name="AutoExecuteScript" Type="System.Boolean" Default="False" Category="02. Options"
Description="Whether or not to immediately execute the script on the target database." %>
<%@ Property Name="ExcludedColumns" Type="StringCollection" Default="" Optional="True" Category="02. Options"
Description="If supplied, any columns in this List will be excluded from all stored procedures unless the column is part of the primary key. (* is treated as a wildcard)" %>
<%@ Property Name="ReadOnlyColumns" Type="StringCollection" Default="" Optional="True" Category="02. Options"
Description="If supplied, any columns in this List will be treated as read only. (* is treated as a wildcard)" %>
<%@ Property Name="ExcludedInsertColumns" Type="StringCollection" Default="ModifiedDate,ModifiedBy,ModifiedNotes,DeletedDate,DeletedBy,DeletedNotes,CancelledDate,CancelledBy,CancelledNotes" Optional="True" Category="02. Options"
Description="If supplied, any columns in this list will be excluded from all insert statements (usually timestamps)." %>
<%@ Property Name="ExcludedUpdateColumns" Type="StringCollection" Default="CreatedDate,CreatedBy,CreatedNotes" Optional="True" Category="02. Options"
Description="If supplied, any columns in this list will be excluded from all update statements (usually timestamps)." %>
<%@ Property Name="ForXml" Type="ForXmlEnum" Default="None" Category="02. Options"
Description="Determines whether to use FOR XML with select statements." %>
<%@ Property Name="IncludeRecordCount" Type="System.Boolean" Default="true" Category="02. Options"
Description="Determines whether to retrieve Total Count." %>
<%@ Property Name="UseSelectCountAllProcedure" Type="System.Boolean" Default="True" Category="02. Options"
Description="If true, this ensures the 'SelectCountAll' procedure is used. Otherwise, a select statement is used instead of a call to the 'SelectCountAll' procedure." %>
<%@ Property Name="IncludeJoinStatements" Type="System.Boolean" Default="True" Optional="True" Category="02. Options"
Description="If true, will create join statements tables." %>
<%@ Property Name="IncludeForeignKeyNameCandidate" Type="System.Boolean" Default="True" Optional="True" Category="02. Options"
Description="If including join statements, this will import a candidate name column (i.e. any column with 'name' or 'title' in the name)." %>
<%@ Property Name="DefaultRowCount" Type="System.Int32" Default="1" Category="02. Options"
Description="Determines the default number of records to return when none is specified (or is not valid)." %>
<%@ Property Name="DefaultPageNumber" Type="System.Int32" Default="1" Category="02. Options"
Description="Determines the default page to be used when none is specified (or is not valid)." %>
<%@ Property Name="DefaultPageSize" Type="System.Int32" Default="10" Category="02. Options"
Description="Determines the default page size to return when none is specified (or is not valid)." %>
<%@ Property Name="MaxStringLength" Type="System.Int32" Default="4000" Category="02. Options"
Description="The maximum size of string before column is commented in paged sets." %>
<%-- Procedure Types --%>
<%-- Insert Procedures --%>
<%@ Property Name="IncludeInsert" Type="System.Boolean" Default="True" Category="03. Insert Procedure"
Description="If true an INSERT procedure will be generated." %>
<%@ Property Name="IncludeInsertAll" Type="System.Boolean" Default="True" Category="03. Insert Procedure"
Description="If true an INSERT procedure will be generated to insert all 1-1 mapped information." %>
<%-- Update Procedures --%>
<%@ Property Name="IncludeUpdate" Type="System.Boolean" Default="True" Category="04. Update Procedures"
Description="If true an UPDATE procedure will be generated." %>
<%@ Property Name="IncludeUpdateByUniqueIndex" Type="System.Boolean" Default="True" Category="04. Update Procedures"
Description="If true an UPDATE procedure will be generated for each unique index." %>
<%@ Property Name="IncludeUpdateByUniqueIdentifier" Type="System.Boolean" Default="True" Category="04. Update Procedures"
Description="If true an UPDATE procedure will be generated for each unique idenitifier." %>
<%@ Property Name="IncludeUpdateBitColumns" Type="System.Boolean" Default="True" Category="04. Update Procedures"
Description="If true an UPDATE procedure will be generated for each bit (or Bitged) column." %>
<%@ Property Name="IncludeUpdateAll" Type="System.Boolean" Default="True" Category="04. Update Procedures"
Description="If true an UPDATE procedure will be generated to insert all 1-1 mapped information." %>
<%-- Delete Procedures --%>
<%@ Property Name="IncludeDeleteAll" Type="System.Boolean" Default="True" Category="05. Delete Procedures"
Description="If true a DELETE all procedure will be generated." %>
<%@ Property Name="IncludeDelete" Type="System.Boolean" Default="True" Category="05. Delete Procedures"
Description="If true a DELETE procedure will be generated." %>
<%@ Property Name="IncludeDeleteByForeignKey" Type="System.Boolean" Default="True" Category="05. Delete Procedures"
Description="If true a DELETE by Bit procedure will be generated to handle all bit (or Bitged) columns." %>
<%@ Property Name="IncludeDeleteByBitColumn" Type="System.Boolean" Default="True" Category="05. Delete Procedures"
Description="If true a DELETE by Bit procedure will be generated to handle all bit (or Bitged) columns." %>
<%--@ Property Name="IncludeDeleteByIndex" Type="System.Boolean" Default="True" Category="05. Delete Procedures"
Description="If true a DELETE by unique index procedure will be generated for each unique index." --%>
<%@ Property Name="IncludeDeleteByUniqueIndex" Type="System.Boolean" Default="True" Category="05. Delete Procedures"
Description="If true a DELETE by unique identifier procedure will be generated for each unique identifier." %>
<%@ Property Name="IncludeDeleteByUniqueIdentifier" Type="System.Boolean" Default="True" Category="05. Delete Procedures"
Description="If true a DELETE by unique index procedure will be generated for each unique index." %>
<%@ Property Name="IncludeDeleteBy" Type="System.Boolean" Default="True" Category="05. Delete Procedures"
Description="If true a DELETE procedure will be generated to handle all foreign keys, bit columns, unique and column indexes." %>
<%-- Select Procedures --%>
<%@ Property Name="IncludeSelectAll" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT all procedure will be generated." %>
<%@ Property Name="IncludeSelect" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT procedure will be generated." %>
<%@ Property Name="IncludeSelectUsingOutParameters" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT procedure will be generated and data returned in output parameters." %>
<%@ Property Name="IncludeSelectByForeignKey" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT by foreign key procedure will be generated for each foreign key." %>
<%@ Property Name="IncludeSelectByBitColumn" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT by Bit procedure will be generated to handle each foreign key." %>
<%--@ Property Name="IncludeSelectByIndex" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT by index procedure will be generated to handle each table index." --%>
<%@ Property Name="IncludeSelectByUniqueIndex" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT by unique index procedure will be generated to handle each unique table index." %>
<%@ Property Name="IncludeSelectByUniqueIdentifier" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT by unique identifier procedure will be generated to handle each unique identifier." %>
<%@ Property Name="IncludeSelectBy" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT procedure will be generated to handle all foreign keys, bit columns, unique and column indexes." %>
<%-- Select Search Procedures --%>
<%@ Property Name="IncludeSelectSearchAll" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT SEARCH all procedure will be generated." %>
<%@ Property Name="IncludeSelectSearchByForeignKey" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT SEARCH by foreign key procedure will be generated for each foreign key." %>
<%@ Property Name="IncludeSelectSearchByBitColumn" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT SEARCH by Bit procedure will be generated to handle each foreign key." %>
<%@ Property Name="IncludeSelectSearchBy" Type="System.Boolean" Default="True" Category="07. Select Procedures"
Description="If true a SELECT SEARCH procedure will be generated to handle all foreign keys, bit columns, unique and column indexes." %>
<%-- Select Unique Index and Primary Key Procedures --%>
<%@ Property Name="IncludeSelectUniqueIndexByPrimaryKey" Type="System.Boolean" Default="True" Category="08. Select Index and Primary Key Procedures"
Description="If true a SELECT procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectUniqueIdentifierByPrimaryKey" Type="System.Boolean" Default="True" Category="08. Select Index and Primary Key Procedures"
Description="If true a SELECT procedure will be generated to retrieve the unique identifier using the primary key." %>
<%@ Property Name="IncludeSelectPrimaryKeyByUniqueIndex" Type="System.Boolean" Default="True" Category="08. Select Index and Primary Key Procedures"
Description="If true a SELECT procedure will be generated to retrieve the primary key value using the unique index." %>
<%@ Property Name="IncludeSelectPrimaryKeyByUniqueIdentifier" Type="System.Boolean" Default="True" Category="08. Select Index and Primary Key Procedures"
Description="If true a SELECT procedure will be generated to retrieve the primary key value using the unique identifier." %>
<%-- Select RowCount Procedures --%>
<%@ Property Name="IncludeSelectUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT procedure will be generated." %>
<%@ Property Name="IncludeSelectByForeignKeyUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT procedure will be generated for each foreign key." %>
<%@ Property Name="IncludeSelectByBitColumnUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT procedure will be generated for each foreign key." %>
<%--@ Property Name="IncludeSelectByIndexUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT procedure will be generated for each index." --%>
<%@ Property Name="IncludeSelectByUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT procedure will be generated to handle all foreign keys, bit columns, unique and column indexes." %>
<%-- Select Search RowCount Procedures --%>
<%@ Property Name="IncludeSelectSearchUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT SEARCH procedure will be generated." %>
<%@ Property Name="IncludeSelectSearchByForeignKeyUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT SEARCH procedure will be generated for each foreign key." %>
<%@ Property Name="IncludeSelectSearchByBitColumnUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT SEARCH procedure will be generated for each foreign key." %>
<%@ Property Name="IncludeSelectSearchByUsingRowCount" Type="System.Boolean" Default="True" Category="09. Select RowCount Procedures"
Description="If true a ROWCOUNT SELECT SEARCH procedure will be generated to handle all foreign keys, bit columns, unique and column indexes." %>
<%-- Select List Procedures --%>
<%@ Property Name="IncludeSelectList" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectListByForeignKey" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." %>
<%--@ Property Name="IncludeSelectListByIndex" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." --%>
<%@ Property Name="IncludeSelectListByBitColumn" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectListBy" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectListUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectListByForeignKeyUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." %>
<%--@ Property Name="IncludeSelectListByIndexUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." --%>
<%@ Property Name="IncludeSelectListByBitColumnUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectListByUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT List procedure will be generated to retrieve the unique index using the primary key." %>
<%-- Select Search List Procedures --%>
<%@ Property Name="IncludeSelectSearchList" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT SEARCH LIST procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectSearchListByForeignKey" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT SEARCH LIST procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectSearchListByBitColumn" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT SEARCH LIST procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectSearchListBy" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT LIST procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectSearchListUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT SEARCH LIST procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectSearchListByForeignKeyUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT SEARCH LIST procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectSearchListByBitColumnUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT SEARCH LIST procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectSearchListByUsingRowCount" Type="System.Boolean" Default="True" Category="10. Select List Procedures"
Description="If true a SELECT SEARCH LIST procedure will be generated to retrieve the unique index using the primary key." %>
<%-- Select Random Procedures --%>
<%@ Property Name="IncludeSelectRandom" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a SELECT RANDOM procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectRandomUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM procedure will be generated to retrieve random data using the specified row count." %>
<%@ Property Name="IncludeSelectRandomByForeignKeyUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM procedure will be generated to retrieve random data using the specified rowcount and to handle each table foreign key." %>
<%--@ Property Name="IncludeSelectRandomByIndexUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM procedure will be generated to retrieve random data using the specified rowcount and to handle each table foreign key." --%>
<%@ Property Name="IncludeSelectRandomByBitColumnUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM procedure will be generated to retrieve random data using the specified rowcount and to handle each table foreign key." %>
<%@ Property Name="IncludeSelectRandomByUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM procedure will be generated to retrieve random data using the specified rowcount and to handle each table foreign key." %>
<%@ Property Name="IncludeSelectRandomPrimaryKey" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a SELECT RANDOM procedure will be generated to retrieve a random primary key." %>
<%@ Property Name="IncludeSelectRandomPrimaryKeyUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a SELECT RANDOM procedure will be generated to retrieve the specified number of random primary key records." %>
<%@ Property Name="IncludeSelectRandomUniqueIndex" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a SELECT RANDOM procedure will be generated to retrieve a random primary key." %>
<%@ Property Name="IncludeSelectRandomUniqueIndexUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a SELECT RANDOM procedure will be generated to retrieve the specified number of random primary key records." %>
<%-- Select Search Random Procedures --%>
<%@ Property Name="IncludeSelectSearchRandom" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a SELECT RANDOM SEARCH procedure will be generated to retrieve the unique index using the primary key." %>
<%@ Property Name="IncludeSelectSearchRandomUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM SEARCH procedure will be generated to retrieve random data using the specified row count." %>
<%@ Property Name="IncludeSelectSearchRandomByForeignKeyUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM SEARCH procedure will be generated to retrieve random data using the specified rowcount and to handle each table foreign key." %>
<%@ Property Name="IncludeSelectSearchRandomByBitColumnUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM SEARCH procedure will be generated to retrieve random data using the specified rowcount and to handle each table foreign key." %>
<%@ Property Name="IncludeSelectSearchRandomByUsingRowCount" Type="System.Boolean" Default="True" Category="11. Select Random Procedures"
Description="If true a ROWCOUNT SELECT RANDOM SEARCH procedure will be generated to retrieve random data using the specified rowcount and to handle each table foreign key." %>
<%-- Select Paged Procedures --%>
<%@ Property Name="IncludeSelectPaged" Type="System.Boolean" Default="True" Category="12. Select Paged Procedures"
Description="If true a SELECT PAGED procedure will be generated to return a paged set." %>
<%@ Property Name="IncludeSelectPagedByForeignKey" Type="System.Boolean" Default="True" Category="12. Select Paged Procedures"
Description="If true a SELECT PAGED procedure will be generated to return a paged set for each foreign key." %>
<%@ Property Name="IncludeSelectPagedByBitColumn" Type="System.Boolean" Default="True" Category="12. Select Paged Procedures"
Description="If true a SELECT PAGED procedure will be generated to return a paged set for each foreign key." %>
<%--@ Property Name="IncludeSelectPagedByIndex" Type="System.Boolean" Default="True" Category="12. Select Paged Procedures"
Description="If true a SELECT PAGED procedure will be generated to return a paged set for each index." --%>
<%@ Property Name="IncludeSelectPagedBy" Type="System.Boolean" Default="True" Category="12. Select Paged Procedures"
Description="If true a SELECT PAGED procedure will be generated to return a paged set to handle all foreign keys, bit columns and indexes." %>
<%-- Select Paged Numbers Procedures --%>
<%@ Property Name="IncludeSelectPagedPageNumber" Type="System.Boolean" Default="True" Category="13. Select Paged Number Procedures"
Description="If true a SELECT PAGED procedure will be generated to return the paged set page number using the primary key." %>
<%@ Property Name="IncludeSelectPagedPageNumberByForeignKey" Type="System.Boolean" Default="True" Category="13. Select Paged Number Procedures"
Description="If true a SELECT PAGED procedure will be generated to return the paged set page number using the primary key." %>
<%@ Property Name="IncludeSelectPagedPageNumberByBitColumn" Type="System.Boolean" Default="True" Category="13. Select Paged Number Procedures"
Description="If true a SELECT PAGED procedure will be generated to return the paged set page number using the primary key." %>
<%@ Property Name="IncludeSelectPagedPageNumberBy" Type="System.Boolean" Default="True" Category="13. Select Paged Number Procedures"
Description="If true a SELECT PAGED procedure will be generated to return the paged set page number using the primary key." %>
<%-- Select Paged Search Procedures --%>
<%@ Property Name="IncludeSelectPagedSearch" Type="System.Boolean" Default="True" Category="14. Select Paged Search Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return a paged set corresponding to search term." %>
<%@ Property Name="IncludeSelectPagedSearchByForeignKey" Type="System.Boolean" Default="True" Category="14. Select Paged Search Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return a paged set corresponding to search term for each foreign key." %>
<%@ Property Name="IncludeSelectPagedSearchByBitColumn" Type="System.Boolean" Default="True" Category="14. Select Paged Search Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return a paged set corresponding to search term for each foreign key." %>
<%--@ Property Name="IncludeSelectPagedSearchByIndex" Type="System.Boolean" Default="True" Category="14. Select Paged Search Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return a paged set corresponding to search term for each index." --%>
<%@ Property Name="IncludeSelectPagedSearchBy" Type="System.Boolean" Default="True" Category="14. Select Paged Search Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return a paged set corresponding to search term to handle all foreign keys, bit columns and indexes." %>
<%-- Select Paged Search Numbers Procedures --%>
<%@ Property Name="IncludeSelectPagedSearchPageNumber" Type="System.Boolean" Default="True" Category="15. Select Paged Search Number Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return the searched paged set page number using the primary key." %>
<%@ Property Name="IncludeSelectPagedSearchPageNumberByForeignKey" Type="System.Boolean" Default="True" Category="15. Select Paged Search Number Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return the searched paged set page number using the primary key." %>
<%@ Property Name="IncludeSelectPagedSearchPageNumberByBitColumn" Type="System.Boolean" Default="True" Category="15. Select Paged Search Number Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return the searched paged set page number using the primary key." %>
<%@ Property Name="IncludeSelectPagedSearchPageNumberBy" Type="System.Boolean" Default="True" Category="15. Select Paged Search Number Procedures"
Description="If true a SELECT PAGED SEARCH procedure will be generated to return the searched paged set page number using the primary key." %>
<%-- Select Count Procedures --%>
<%@ Property Name="IncludeSelectCountAll" Type="System.Boolean" Default="True" Category="16. Select Count Procedures"
Description="If true a SELECT COUNT all procedure will be generated." %>
<%@ Property Name="IncludeSelectCountByForeignKey" Type="System.Boolean" Default="True" Category="16. Select Count Procedures"
Description="If true a SELECT COUNT by foreign key procedure will be generated for each foreign key." %>
<%@ Property Name="IncludeSelectCountByBitColumn" Type="System.Boolean" Default="True" Category="16. Select Count Procedures"
Description="If true a SELECT COUNT by Bit procedure will be generated to handle each foreign key." %>
<%--@ Property Name="IncludeSelectCountByIndex" Type="System.Boolean" Default="True" Category="16. Select Count Procedures"
Description="If true a SELECT COUNT by index procedure will be generated to handle each table index." --%>
<%@ Property Name="IncludeSelectCountBy" Type="System.Boolean" Default="True" Category="16. Select Count Procedures"
Description="If true a SELECT COUNT procedure will be generated to handle all foreign keys, bit columns, unique and column indexes." %>
<%-- Select Count Search Procedures --%>
<%@ Property Name="IncludeSelectCountSearch" Type="System.Boolean" Default="True" Category="17. Select Count Procedures"
Description="If true a SELECT COUNT SEARCH procedure will be generated to return a set corresponding to search term." %>
<%@ Property Name="IncludeSelectCountSearchByForeignKey" Type="System.Boolean" Default="True" Category="17. Select Count Procedures"
Description="If true a SELECT COUNT SEARCH procedure will be generated to return a set corresponding to search term for each foreign key." %>
<%@ Property Name="IncludeSelectCountSearchByBitColumn" Type="System.Boolean" Default="True" Category="17. Select Count Procedures"
Description="If true a SELECT COUNT SEARCH procedure will be generated to return a set corresponding to search term for each foreign key." %>
<%@ Property Name="IncludeSelectCountSearchBy" Type="System.Boolean" Default="True" Category="17. Select Count Procedures"
Description="If true a SELECT COUNT SEARCH procedure will be generated to return a set corresponding to search term to handle all foreign keys, bit columns and indexes." %>
<%-- Set Procedures --%>
<%@ Property Name="IncludeSetNullableDateColumns" Type="System.Boolean" Default="True" Category="18. Set Procedures"
Description="If true a SET procedure will be generated for all nullable date columns." %>
<%-- Assembly References --%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
<%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Assembly Name="System.Data" %>
<%-- Namespace Imports --%>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="CodeSmith.BaseTemplates" %>
<%@ Import Namespace="CodeSmith.CustomProperties" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%
this.Progress.MaximumValue = 20;
this.Progress.Step = 1;
// this template requires a primary key on the source table
if (!this.SourceTable.HasPrimaryKey)
throw new ApplicationException("The source table [" + this.SourceTable.Name + "] does not contain a primary key.");
// this template requires a maximum size be defined for paged setts
if (this.MaxStringLength < 1)
throw new ApplicationException("A maximum string length[ie. MaxStringLength] must be specified.");
//stores all foreign keys, unique index, indexes and bit columsn
ColumnSchemaCollection uniqueIndexColumns = GetUniqueIndexColumns(this.SourceTable);
ColumnSchemaCollection uniqueIdentifierColumns = GetUniqueIdentifierColumns(this.SourceTable);
ColumnSchemaCollection fkColumns = this.SourceTable.ForeignKeyColumns;
ColumnSchemaCollection nonUniqueIndexColumns = GetNonUniqueIndexedColumns(this.SourceTable);
ColumnSchemaCollection bitColumns = GetColumnsByDbType(this.SourceTable.NonKeyColumns, DbType.Boolean);
ColumnSchemaCollection dateColumns = GetColumnsByDbType(this.SourceTable.NonKeyColumns, DbType.DateTime);
ColumnSchemaCollection nullableDateColumns = FilterReadOnlyAndExcludedColumns(GetNullableDateColumns(this.SourceTable));
ColumnSchemaCollection currencyColumns = GetColumnsByDbType(this.SourceTable.NonKeyColumns, DbType.Currency);
ColumnSchemaCollection shortColumns = GetColumnsByDbType(this.SourceTable.NonKeyColumns, DbType.Int16);
ColumnSchemaCollection intColumns = GetColumnsByDbType(this.SourceTable.NonKeyColumns, DbType.Int32);
ColumnSchema nameTitleCandidateColumn = this.GetNameTitleColumnCandidate(this.SourceTable);
ColumnSchemaCollection nameTitleCandidateColumns = new ColumnSchemaCollection(); //collection for remove duplicates.
nameTitleCandidateColumns.Add(nameTitleCandidateColumn);
//stores all foreign key, index and bit columns
//ColumnSchemaCollection keyIndexAndBitColumns = RemoveDuplicateColumns(new ColumnSchemaCollection[]{fkColumns, uniqueIndexColumns, nonUniqueIndexColumns, bitColumns});
ColumnSchemaCollection keyAndBitColumns = RemoveDuplicateColumns(new ColumnSchemaCollection[]{fkColumns, bitColumns});
ColumnSchemaCollection searchableColumns = FilterSearchableColumns(this.SourceTable.Columns);
//sortable columns
ColumnSchemaCollection sortableColumns = RemoveDuplicateColumns(new ColumnSchemaCollection[]{this.SourceTable.PrimaryKey.MemberColumns, keyAndBitColumns, dateColumns, shortColumns, intColumns, currencyColumns, nameTitleCandidateColumns});
//get indexes
IndexSchemaCollection uniqueIndexes = GetUniqueIndexes(this.SourceTable);
IndexSchemaCollection nonUniqueIndexes = GetNonUniqueIndexes(this.SourceTable);
//flags to indicate foreign keys, unique index, indexes and bit columsn
bool hasUniqueIndexes = (uniqueIndexes.Count > 0);
bool hasUniqueIdentifiers = (uniqueIdentifierColumns.Count > 0);
bool hasForeignKeys = (fkColumns.Count > 0);
bool hasNonUniqueIndexes = (nonUniqueIndexes.Count > 0);
bool hasBits = (bitColumns.Count > 0);
bool hasKeyAndBitColumns = (hasForeignKeys || hasNonUniqueIndexes || hasBits);
bool hasNameTitleColumnCandidate = (null != nameTitleCandidateColumn);
bool isMappingTable = IsMappingTable(this.SourceTable); //contains only key columns.
bool hasDateColumns = (dateColumns.Count > 0);
bool hasNullableDateColumns = (hasDateColumns && nullableDateColumns.Count > 0);
bool hasSortableColumns = (null != sortableColumns && sortableColumns.Count > 0);
bool hasSearchableColumns = (null != searchableColumns && searchableColumns.Count > 0);
//flag to indicate whether to use table owner in statements e.g. [dbo].[exampletable]
bool includeTableOwner = true; //hasForeignKeys;
// generate drop statements
if (this.IncludeDropStatements)
{
Response.WriteLine("--region Drop Existing Procedures");
Response.WriteLine("");
//drop insert procedures
if (this.IncludeInsert)
GenerateDropStatement(GetInsertProcedureName());
if (this.IncludeInsertAll)
GenerateDropStatement(GetInsertAllProcedureName());
//drop update procedures
if (this.IncludeUpdate)
GenerateDropStatement(GetUpdateProcedureName());
if (this.IncludeUpdateBitColumns && hasBits)
GenerateDropStatement(GetUpdateBitColumnProcedureName());
if (this.IncludeUpdateByUniqueIndex && hasUniqueIndexes)
{
foreach(IndexSchema indexSchema in uniqueIndexes)
GenerateDropStatement(GetUpdateByUniqueIndexProcedureName(indexSchema.MemberColumns));
}
if (this.IncludeUpdateByUniqueIdentifier && hasUniqueIdentifiers)
{
foreach(ColumnSchema column in uniqueIdentifierColumns)
GenerateDropStatement(GetUpdateByUniqueIdentifierProcedureName(column));
}
if (this.IncludeUpdateAll)
GenerateDropStatement(GetUpdateAllProcedureName());
//drop delete procedures
if (this.IncludeDelete)
GenerateDropStatement(GetDeleteProcedureName());
if (this.IncludeDeleteAll)
GenerateDropStatement(GetDeleteAllProcedureName());
if (this.IncludeDeleteByForeignKey && hasForeignKeys)
GenerateDropStatement(GetDeleteByForeignKeyProcedureName());
if (this.IncludeDeleteByBitColumn && hasBits)
GenerateDropStatement(GetDeleteByBitColumnProcedureName());
/*if (this.IncludeDeleteByIndex && hasNonUniqueIndexes)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetDeleteByIndexProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeDeleteByUniqueIndex && hasUniqueIndexes)
{
foreach(IndexSchema indexSchema in uniqueIndexes)
GenerateDropStatement(GetDeleteByUniqueIndexProcedureName(indexSchema.MemberColumns));
}
if (this.IncludeDeleteByUniqueIdentifier && hasUniqueIdentifiers)
{
foreach(ColumnSchema column in uniqueIdentifierColumns)
GenerateDropStatement(GetDeleteByUniqueIdentifierProcedureName(column));
}
if (this.IncludeDeleteBy && hasKeyAndBitColumns)
GenerateDropStatement(GetDeleteByProcedureName());
//drop select procedures
if (this.IncludeSelect)
GenerateDropStatement(GetSelectProcedureName());
if (this.IncludeSelectUsingOutParameters)
GenerateDropStatement(GetSelectUsingOutParametersProcedureName());
if (this.IncludeSelectAll)
GenerateDropStatement(GetSelectAllProcedureName());
if (this.IncludeSelectByForeignKey && hasForeignKeys)
GenerateDropStatement(GetSelectByForeignKeyProcedureName());
if (this.IncludeSelectByBitColumn && hasBits)
GenerateDropStatement(GetSelectByBitColumnProcedureName());
if (this.IncludeSelectByUniqueIndex && hasUniqueIndexes)
{
foreach(IndexSchema indexSchema in uniqueIndexes)
GenerateDropStatement(GetSelectByUniqueIndexProcedureName(indexSchema.MemberColumns));
}
if (this.IncludeSelectByUniqueIdentifier && hasUniqueIdentifiers)
{
foreach(ColumnSchema column in uniqueIdentifierColumns)
GenerateDropStatement(GetSelectByUniqueIdentifierProcedureName(column));
}
/*
if (this.IncludeSelectByIndex && hasNonUniqueIndexes)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetSelectByIndexProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeSelectBy && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectByProcedureName());
//drop select unique index and primary key procedures
if (this.IncludeSelectUniqueIndexByPrimaryKey && hasUniqueIndexes)
{
foreach(IndexSchema indexSchema in uniqueIndexes)
GenerateDropStatement(GetSelectUniqueIndexByPrimaryKeyProcedureName(indexSchema.MemberColumns));
}
//drop select unique identifier
if (this.IncludeSelectUniqueIdentifierByPrimaryKey && hasUniqueIdentifiers)
{
foreach(ColumnSchema column in uniqueIdentifierColumns)
GenerateDropStatement(GetSelectUniqueIdentifierByPrimaryKeyProcedureName(column));
}
if (this.IncludeSelectPrimaryKeyByUniqueIndex && hasUniqueIndexes)
{
foreach(IndexSchema indexSchema in uniqueIndexes)
GenerateDropStatement(GetSelectPrimaryKeyByUniqueIndexProcedureName(indexSchema.MemberColumns));
}
if (this.IncludeSelectPrimaryKeyByUniqueIdentifier && hasUniqueIdentifiers)
{
foreach(ColumnSchema column in uniqueIdentifierColumns)
GenerateDropStatement(GetSelectPrimaryKeyByUniqueIdentifierProcedureName(column));
}
//drop select search procedures
if (this.IncludeSelectSearchAll)
GenerateDropStatement(GetSelectSearchAllProcedureName());
if (this.IncludeSelectSearchByForeignKey && hasForeignKeys)
GenerateDropStatement(GetSelectSearchByForeignKeyProcedureName());
if (this.IncludeSelectSearchByBitColumn && hasBits)
GenerateDropStatement(GetSelectSearchByBitColumnProcedureName());
if (this.IncludeSelectSearchBy && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectSearchByProcedureName());
//drop select list procedures
if (this.IncludeSelectList)
GenerateDropStatement(GetSelectListProcedureName());
if (this.IncludeSelectListByForeignKey && hasForeignKeys)
GenerateDropStatement(GetSelectListByForeignKeyProcedureName());
if (this.IncludeSelectListByBitColumn && hasBits)
GenerateDropStatement(GetSelectListByBitColumnProcedureName());
/*if (this.IncludeSelectListByIndex && hasNonUniqueIndexes)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetSelectListByIndexProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeSelectListBy && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectListByProcedureName());
if (this.IncludeSelectListUsingRowCount)
GenerateDropStatement(GetSelectListUsingRowCountProcedureName());
if (this.IncludeSelectListByForeignKeyUsingRowCount && hasForeignKeys)
GenerateDropStatement(GetSelectListByForeignKeyUsingRowCountProcedureName());
if (this.IncludeSelectListByBitColumnUsingRowCount && hasBits)
GenerateDropStatement(GetSelectListByBitColumnUsingRowCountProcedureName());
/*if (this.IncludeSelectListByIndexUsingRowCount && hasNonUniqueIndexes)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetSelectListByIndexUsingRowCountProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeSelectListByUsingRowCount && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectListByUsingRowCountProcedureName());
//drop select search list procedures
if (this.IncludeSelectSearchList)
GenerateDropStatement(GetSelectSearchListProcedureName());
if (this.IncludeSelectSearchListByForeignKey && hasForeignKeys)
GenerateDropStatement(GetSelectSearchListByForeignKeyProcedureName());
if (this.IncludeSelectSearchListByBitColumn && hasBits)
GenerateDropStatement(GetSelectSearchListByBitColumnProcedureName());
if (this.IncludeSelectSearchListBy && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectSearchListByProcedureName());
if (this.IncludeSelectSearchListUsingRowCount)
GenerateDropStatement(GetSelectSearchListUsingRowCountProcedureName());
if (this.IncludeSelectSearchListByForeignKeyUsingRowCount && hasForeignKeys)
GenerateDropStatement(GetSelectSearchListByForeignKeyUsingRowCountProcedureName());
if (this.IncludeSelectSearchListByBitColumnUsingRowCount && hasBits)
GenerateDropStatement(GetSelectSearchListByBitColumnUsingRowCountProcedureName());
if (this.IncludeSelectSearchListByUsingRowCount && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectSearchListByUsingRowCountProcedureName());
//drop select random procedures
if (this.IncludeSelectRandom)
GenerateDropStatement(GetSelectRandomProcedureName());
if (this.IncludeSelectRandomUsingRowCount)
GenerateDropStatement(GetSelectRandomUsingRowCountProcedureName());
if (this.IncludeSelectRandomByForeignKeyUsingRowCount)
GenerateDropStatement(GetSelectRandomByForeignKeyUsingRowCountProcedureName());
/*if (this.IncludeSelectRandomByIndexUsingRowCount)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetSelectRandomByIndexUsingRowCountProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeSelectRandomByBitColumnUsingRowCount)
GenerateDropStatement(GetSelectRandomByBitColumnUsingRowCountProcedureName());
if (this.IncludeSelectRandomByUsingRowCount)
GenerateDropStatement(GetSelectRandomByUsingRowCountProcedureName());
if (this.IncludeSelectRandomPrimaryKey)
GenerateDropStatement(GetSelectRandomPrimaryKeyProcedureName());
if (this.IncludeSelectRandomPrimaryKeyUsingRowCount)
GenerateDropStatement(GetSelectRandomPrimaryKeyUsingRowCountProcedureName());
if (this.IncludeSelectRandomUniqueIndex && hasUniqueIndexes)
{
foreach(IndexSchema indexSchema in uniqueIndexes)
GenerateDropStatement(GetSelectRandomUniqueIndexProcedureName(indexSchema.MemberColumns));
}
if (this.IncludeSelectRandomUniqueIndexUsingRowCount && hasUniqueIndexes)
{
foreach(IndexSchema indexSchema in uniqueIndexes)
GenerateDropStatement(GetSelectRandomUniqueIndexUsingRowCountProcedureName(indexSchema.MemberColumns));
}
//drop select search random procedures
if (this.IncludeSelectSearchRandom)
GenerateDropStatement(GetSelectSearchRandomProcedureName());
if (this.IncludeSelectSearchRandomUsingRowCount)
GenerateDropStatement(GetSelectSearchRandomUsingRowCountProcedureName());
if (this.IncludeSelectSearchRandomByForeignKeyUsingRowCount)
GenerateDropStatement(GetSelectSearchRandomByForeignKeyUsingRowCountProcedureName());
if (this.IncludeSelectSearchRandomByBitColumnUsingRowCount)
GenerateDropStatement(GetSelectSearchRandomByBitColumnUsingRowCountProcedureName());
if (this.IncludeSelectSearchRandomByUsingRowCount)
GenerateDropStatement(GetSelectSearchRandomByUsingRowCountProcedureName());
//drop select rowcount procedures
if (this.IncludeSelectUsingRowCount)
GenerateDropStatement(GetSelectRowCountProcedureName());
if (this.IncludeSelectByForeignKeyUsingRowCount && hasForeignKeys)
GenerateDropStatement(GetSelectRowCountByForeignKeyProcedureName());
if (this.IncludeSelectByBitColumnUsingRowCount && hasBits)
GenerateDropStatement(GetSelectRowCountByBitColumnProcedureName());
/*if (this.IncludeSelectByIndexUsingRowCount && hasNonUniqueIndexes)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetSelectRowCountByIndexProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeSelectByUsingRowCount && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectRowCountByProcedureName());
//drop select search rowcount procedures
if (this.IncludeSelectSearchUsingRowCount)
GenerateDropStatement(GetSelectSearchRowCountProcedureName());
if (this.IncludeSelectSearchByForeignKeyUsingRowCount && hasForeignKeys)
GenerateDropStatement(GetSelectSearchRowCountByForeignKeyProcedureName());
if (this.IncludeSelectSearchByBitColumnUsingRowCount && hasBits)
GenerateDropStatement(GetSelectSearchRowCountByBitColumnProcedureName());
if (this.IncludeSelectSearchByUsingRowCount && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectSearchRowCountByProcedureName());
//drop select paged procedures
if (this.IncludeSelectPaged)
GenerateDropStatement(GetSelectPagedProcedureName());
if (this.IncludeSelectPagedByForeignKey && hasForeignKeys)
GenerateDropStatement(GetSelectPagedByForeignKeyProcedureName());
if (this.IncludeSelectPagedByBitColumn && hasBits)
GenerateDropStatement(GetSelectPagedByBitColumnProcedureName());
/*if (this.IncludeSelectPagedByIndex && hasNonUniqueIndexes)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetSelectPagedByIndexProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeSelectPagedBy && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectPagedByProcedureName());
//drop select paged search procedures
if (this.IncludeSelectPagedSearch)
GenerateDropStatement(GetSelectPagedSearchProcedureName());
if (this.IncludeSelectPagedSearchByForeignKey && hasForeignKeys)
GenerateDropStatement(GetSelectPagedSearchByForeignKeyProcedureName());
if (this.IncludeSelectPagedSearchByBitColumn && hasBits)
GenerateDropStatement(GetSelectPagedSearchByBitColumnProcedureName());
/*if (this.IncludeSelectPagedSearchByIndex && hasNonUniqueIndexes)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetSelectPagedSearchByIndexProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeSelectPagedSearchBy && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectPagedSearchByProcedureName());
//drop select count procedures
if (this.IncludeSelectCountAll)
GenerateDropStatement(GetSelectCountAllProcedureName());
if (this.IncludeSelectCountByForeignKey && hasForeignKeys)
GenerateDropStatement(GetSelectCountByForeignKeyProcedureName());
if (this.IncludeSelectCountByBitColumn && hasBits)
GenerateDropStatement(GetSelectCountByBitColumnProcedureName());
/*if (this.IncludeSelectCountByIndex && hasNonUniqueIndexes)
{
foreach(IndexSchema indexSchema in nonUniqueIndexes)
GenerateDropStatement(GetSelectCountByIndexProcedureName(indexSchema.MemberColumns));
}*/
if (this.IncludeSelectCountBy && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectCountByProcedureName());
if (this.IncludeSelectCountSearch)
GenerateDropStatement(GetSelectCountSearchProcedureName());
if (this.IncludeSelectCountSearchByForeignKey && hasForeignKeys)
GenerateDropStatement(GetSelectCountSearchByForeignKeyProcedureName());
if (this.IncludeSelectCountSearchByBitColumn && hasBits)
GenerateDropStatement(GetSelectCountSearchByBitColumnProcedureName());
if (this.IncludeSelectCountSearchBy && hasKeyAndBitColumns)
GenerateDropStatement(GetSelectCountSearchByProcedureName());
if (this.IncludeSetNullableDateColumns && hasNullableDateColumns)
{
foreach(ColumnSchema column in nullableDateColumns)
GenerateDropStatement(GetSetNullableDateColumnProcedureName(column));
}
Response.WriteLine("--endregion");
Response.WriteLine("");
Response.WriteLine("GO");
Response.WriteLine("");
this.Progress.PerformStep();
}
%>
<%
//stores procedure name
string procedureName;
%>
<%------------------------------------------------------------------------------------------
*
* Insert Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeInsert)
{
procedureName = GetInsertProcedureName();
GenerateProcedureHeader(procedureName);
/*
* Check to see if the primary key is a single column primary key and also if it's either an
* identity column or a GUID. If so, we will not include the primary key column in the
* List of input parameters.
*/
if (this.SourceTable.PrimaryKey.MemberColumns.Count == 1
&& (this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Guid
|| ((this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int16
|| this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int32
|| this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int64)
&& (bool)this.SourceTable.PrimaryKey.MemberColumns[0].ExtendedProperties["CS_IsIdentity"].Value == true)))
{
//is identity primary key (i.e. single key, int, identity) so get zero index
ColumnSchema primaryKeyColumn = this.SourceTable.PrimaryKey.MemberColumns[0];
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key output
<% GenerateParameter(primaryKeyColumn, 1, true, false, true); %>
-- other columns
<% GenerateParameters(FilterExcludedInsertColumns(this.SourceTable.NonPrimaryKeyColumns), 1, true, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
<%-- If the primary key is a GUID, then assign a new GUID using NEWID(). --%>
<% if (primaryKeyColumn.DataType == DbType.Guid) { %>
SET @<%= primaryKeyColumn.Name %> = NEWID()
<% } %>
-- system function stores
DECLARE
@ReturnValue int,
@ErrStatus int -- stores error status
<% if (hasUniqueIndexes){ %>
/* -------------------------------------------------------------
* Check if unique index already exists.
* ------------------------------------------------------------- */
IF EXISTS
(
SELECT
NULL
FROM
<%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
WHERE
<% GenerateConditions(uniqueIndexColumns, 3, includeTableOwner); %>
)
BEGIN
/* -------------------------------------------------------------
* Return existing key.
* ------------------------------------------------------------- */
SELECT
@<%= primaryKeyColumn.Name %> = <% GenerateColumn(primaryKeyColumn, -1, true, true, true, false, false, false, false); %>
FROM
<%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
WHERE
<% GenerateConditions(uniqueIndexColumns, 3, includeTableOwner); %>
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
-- return already exists.
RETURN -2
END
ELSE
<% } %>
BEGIN
/* -------------------------------------------------------------
* DML Insert w/ auto key
* ------------------------------------------------------------- */
INSERT INTO <%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
(
<% if (primaryKeyColumn.DataType == DbType.Guid) { %>
[<%= primaryKeyColumn.Name %>],
<% } %>
<% GenerateColumns(FilterExcludedInsertColumns(this.SourceTable.NonPrimaryKeyColumns), 3, true, true, false); %>
)
VALUES
(
<% if (primaryKeyColumn.DataType == DbType.Guid) { %>
@<%= primaryKeyColumn.Name %>,
<% } %>
<% GenerateVariables(FilterExcludedInsertColumns(this.SourceTable.NonPrimaryKeyColumns), 3); %>
)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
<%-- If the primary key is an identity column, then capture the newly assigned identity using SCOPE_IDENTITY(). --%>
<% if (primaryKeyColumn.DataType == DbType.Int16 || primaryKeyColumn.DataType == DbType.Int32 || primaryKeyColumn.DataType == DbType.Int64) { %>
-- output primary key (use SCOPE_IDENTITY to avoid concurrency problems)
SET @<%= primaryKeyColumn.Name %> = SCOPE_IDENTITY()
<% } %>
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- return value
RETURN 0
<%-- Primary key is not a identity column or a GUID, so include all columns as input parameters. --%>
<% } else { %>
CREATE PROCEDURE <%= procedureName %>
-- primary key
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true); %>
-- non primary key columns
<% GenerateParameters(FilterExcludedInsertColumns(this.SourceTable.NonPrimaryKeyColumns), 1, true, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check if key already exists.
* ------------------------------------------------------------- */
IF EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
-- return already exists
RETURN -1
END
<% if (hasUniqueIndexes){ %>
/* -------------------------------------------------------------
* Check if unique index already exists.
* ------------------------------------------------------------- */
ELSE IF EXISTS
(
SELECT
NULL
FROM
<%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
WHERE
<% GenerateConditions(uniqueIndexColumns, 3, includeTableOwner); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
-- return uindex already exists
RETURN -2
END
ELSE
<% } %>
BEGIN
<% if (ColumnIsTextual(this.SourceTable.PrimaryKey.MemberColumns[0])) { %>
-- string based keys
<%
for(int i=0; i<this.SourceTable.PrimaryKey.MemberColumns.Count; i++)
{
if (this.SourceTable.PrimaryKey.MemberColumns[i].Name.ToLower().IndexOf("email") > 0)
{
%>
SET @<%= this.SourceTable.PrimaryKey.MemberColumns[i].Name %> = LOWER(@<%= this.SourceTable.PrimaryKey.MemberColumns[i].Name %>) -- lowercase email
<% }
else if (ColumnIsTextual(this.SourceTable.PrimaryKey.MemberColumns[i]))
{
%>
SET @<%= this.SourceTable.PrimaryKey.MemberColumns[i].Name %> = UPPER(@<%= this.SourceTable.PrimaryKey.MemberColumns[i].Name %>) -- uppercase keys
<% }
}
%>
<% } %>
/* -------------------------------------------------------------
* DML Insert w/ pk specified.
* ------------------------------------------------------------- */
INSERT INTO <%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
(
<% GenerateColumns(FilterExcludedInsertColumns(this.SourceTable.Columns), 3, true, true, false); %>
)
VALUES
(
<% GenerateVariables(FilterExcludedInsertColumns(this.SourceTable.Columns), 3); %>
)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- return success(0)
RETURN 0
<%
}
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Insert All Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeInsertAll)
{
procedureName = GetInsertAllProcedureName();
GenerateProcedureHeader(procedureName);
/*
* Determine if OneToOneMapping.
*/
bool containsOneToOneKey = ContainsOneToOneKey(this.SourceTable);
if (containsOneToOneKey)
{
/*
* Check to see if the primary key is a single column primary key and also if it's either an
* identity column or a GUID. If so, we will not include the primary key column in the
* List of input parameters.
*/
if (this.SourceTable.PrimaryKey.MemberColumns.Count == 1
&& (this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Guid
|| ((this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int16
|| this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int32
|| this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int64)
&& (bool)this.SourceTable.PrimaryKey.MemberColumns[0].ExtendedProperties["CS_IsIdentity"].Value == true)))
{
//is identity primary key (i.e. single key, int, identity) so get zero index
ColumnSchema primaryKeyColumn = this.SourceTable.PrimaryKey.MemberColumns[0];
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key output
<% GenerateParameter(primaryKeyColumn, 1, true, false, true); %>
-- other columns
<% GenerateParameters(FilterExcludedInsertColumns(this.SourceTable.NonPrimaryKeyColumns), 1, true, true); %>
<%
foreach(TableKeySchema keySchema in this.SourceTable.PrimaryKeys)
{
if (IsRelationOneToOne(keySchema))
{
Response.Write("\t-- 1-1 mapped columns for " + keySchema.ForeignKeyTable.Name + "\n");
string prefix = keySchema.ForeignKeyTable.Name + "_";
GenerateParametersWithPrefix(prefix, FilterExcludedInsertColumns(keySchema.ForeignKeyTable.Columns), 1, true, true);
Response.Write("\n");
}
}
%>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
<%-- If the primary key is a GUID, then assign a new GUID using NEWID(). --%>
<% if (primaryKeyColumn.DataType == DbType.Guid) { %>
SET @<%= primaryKeyColumn.Name %> = NEWID()
<% } %>
-- system function stores
DECLARE
@ReturnValue int,
@ErrStatus int -- stores error status
<% if (hasUniqueIndexes){ %>
/* -------------------------------------------------------------
* Check if unique index already exists.
* ------------------------------------------------------------- */
IF EXISTS
(
SELECT
NULL
FROM
<%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
WHERE
<% GenerateConditions(uniqueIndexColumns, 3, includeTableOwner); %>
)
BEGIN
/* -------------------------------------------------------------
* Return existing key.
* ------------------------------------------------------------- */
SELECT
@<%= primaryKeyColumn.Name %> = <% GenerateColumn(primaryKeyColumn, -1, true, true, true, false, false, false, false); %>
FROM
<%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
WHERE
<% GenerateConditions(uniqueIndexColumns, 3, includeTableOwner); %>
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
-- return already exists.
RETURN -2
END
ELSE
<% } %>
BEGIN
/* -------------------------------------------------------------
* DML Insert w/ auto key
* ------------------------------------------------------------- */
INSERT INTO <%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
(
<% if (primaryKeyColumn.DataType == DbType.Guid) { %>
[<%= primaryKeyColumn.Name %>],
<% } %>
<% GenerateColumns(FilterExcludedInsertColumns(this.SourceTable.NonPrimaryKeyColumns), 3, true, true, false); %>
)
VALUES
(
<% if (primaryKeyColumn.DataType == DbType.Guid) { %>
@<%= primaryKeyColumn.Name %>,
<% } %>
<% GenerateVariables(FilterExcludedInsertColumns(this.SourceTable.NonPrimaryKeyColumns), 3); %>
)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
<%-- If the primary key is an identity column, then capture the newly assigned identity using SCOPE_IDENTITY(). --%>
<% if (primaryKeyColumn.DataType == DbType.Int16 || primaryKeyColumn.DataType == DbType.Int32 || primaryKeyColumn.DataType == DbType.Int64) { %>
-- output primary key (use SCOPE_IDENTITY to avoid concurrency problems)
SET @<%= primaryKeyColumn.Name %> = SCOPE_IDENTITY()
<% } %>
-------------------------------------------------------------------------
<%
foreach(TableKeySchema keySchema in this.SourceTable.PrimaryKeys)
{
if (IsRelationOneToOne(keySchema))
{
string prefix = keySchema.ForeignKeyTable.Name + "_";
%>
/* -----------------------------------------------------------------------
* DML Insert 1-1 mapped columns for <%= keySchema.ForeignKeyTable.Name %>
* ----------------------------------------------------------------------- */
INSERT INTO <%= GetTableOwner() %>[<%= keySchema.ForeignKeyTable.Name %>]
(
<% GenerateColumns(FilterExcludedInsertColumns(keySchema.ForeignKeyTable.Columns), 3, true, true, false); %>
)
VALUES
(
<% GenerateVariablesWithPrefix(prefix, FilterExcludedInsertColumns(keySchema.ForeignKeyTable.Columns), 3); %>
)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when inserting 1-1 mapped info to <%= keySchema.ForeignKeyTable.Name %>.', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>'' when inserting 1-1 mapped info to <%= keySchema.ForeignKeyTable.Name %>.', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
<%
}
}
%>
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- return value
RETURN 0
<%-- Primary key is not a identity column or a GUID, so include all columns as input parameters. --%>
<% } else { %>
CREATE PROCEDURE <%= procedureName %>
-- primary key
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true); %>
-- non primary key columns
<% GenerateParameters(FilterExcludedInsertColumns(this.SourceTable.NonPrimaryKeyColumns), 1, true, true); %>
<%
foreach(TableKeySchema keySchema in this.SourceTable.PrimaryKeys)
{
if (IsRelationOneToOne(keySchema))
{
Response.Write("\t-- 1-1 mapped columns for " + keySchema.ForeignKeyTable.Name + "\n");
string prefix = keySchema.ForeignKeyTable.Name + "_";
GenerateParametersWithPrefix(prefix, FilterExcludedInsertColumns(keySchema.ForeignKeyTable.Columns), 1, true, true);
Response.Write("\n");
}
}
%>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check if key already exists.
* ------------------------------------------------------------- */
IF EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
-- return already exists
RETURN -1
END
<% if (hasUniqueIndexes){ %>
/* -------------------------------------------------------------
* Check if unique index already exists.
* ------------------------------------------------------------- */
ELSE IF EXISTS
(
SELECT
NULL
FROM
<%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
WHERE
<% GenerateConditions(uniqueIndexColumns, 3, includeTableOwner); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
-- return uindex already exists
RETURN -2
END
ELSE
<% } %>
BEGIN
<% if (ColumnIsTextual(this.SourceTable.PrimaryKey.MemberColumns[0])) { %>
-- string based keys
<%
for(int i=0; i<this.SourceTable.PrimaryKey.MemberColumns.Count; i++)
{
if (this.SourceTable.PrimaryKey.MemberColumns[i].Name.ToLower().IndexOf("Email")>0)
{
%>
SET @<%= this.SourceTable.PrimaryKey.MemberColumns[i].Name %> = LOWER(@<%= this.SourceTable.PrimaryKey.MemberColumns[i].Name %>) -- lowercase email
<% }
else if (ColumnIsTextual(this.SourceTable.PrimaryKey.MemberColumns[i]))
{
%>
SET @<%= this.SourceTable.PrimaryKey.MemberColumns[i].Name %> = UPPER(@<%= this.SourceTable.PrimaryKey.MemberColumns[i].Name %>) -- uppercase keys
<% }
}
%>
<% } %>
/* -------------------------------------------------------------
* DML Insert w/ pk specified.
* ------------------------------------------------------------- */
INSERT INTO <%= GetTableOwner() %>[<%= this.SourceTable.Name %>]
(
<% GenerateColumns(FilterExcludedInsertColumns(this.SourceTable.Columns), 3, true, true, false); %>
)
VALUES
(
<% GenerateVariables(FilterExcludedInsertColumns(this.SourceTable.Columns), 3); %>
)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
-------------------------------------------------------------------------
<%
foreach(TableKeySchema keySchema in this.SourceTable.PrimaryKeys)
{
if (IsRelationOneToOne(keySchema))
{
string prefix = keySchema.ForeignKeyTable.Name + "_";
%>
/* -----------------------------------------------------------------------
* DML Insert 1-1 mapped columns for <%= keySchema.ForeignKeyTable.Name %>
* ----------------------------------------------------------------------- */
INSERT INTO <%= GetTableOwner() %>[<%= keySchema.ForeignKeyTable.Name %>]
(
<% GenerateColumns(FilterExcludedInsertColumns(keySchema.ForeignKeyTable.Columns), 3, true, true, false); %>
)
VALUES
(
<% GenerateVariablesWithPrefix(prefix, FilterExcludedInsertColumns(keySchema.ForeignKeyTable.Columns), 3); %>
)
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when inserting 1-1 mapped info to <%= keySchema.ForeignKeyTable.Name %>.', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>'' when inserting 1-1 mapped info to <%= keySchema.ForeignKeyTable.Name %>.', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
<%
}
}
%>
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- return success(0)
RETURN 0
<%
}
}//hasOneToOneMapping
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Update Procedures
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeUpdate)
{
procedureName = GetUpdateProcedureName();
GenerateProcedureHeader(procedureName);
bool isSourceOneToOneKey = false; //******************** DETERMINE WHETHER THIS IS A ONE TO ONE TABLE (NOT SOURCE TABLE) e.g. ClubEmail not Club
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true, false); %>
-- columns
<% GenerateParameters(FilterExcludedUpdateColumns(this.SourceTable.NonPrimaryKeyColumns), 1, true, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
)
BEGIN<% if (!isSourceOneToOneKey){ %>
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
<% } else { %>
/* -------------------------------------------------------------
* Insert if none found.
* ------------------------------------------------------------- */
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= GetInsertProcedureName() %><% foreach(ColumnSchema c in this.SourceTable.Columns){ %>
@<%= StringUtil.ToPascalCase(c.Name) %> = @<%= StringUtil.ToPascalCase(c.Name) %>,<% } %>
@RowsAffected = @RowsAffected OUTPUT
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected returned by <%= GetInsertProcedureName() %> when inserted by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
-- must commit!
COMMIT TRANSACTION
-- return
RETURN @ReturnValue
<% } %>
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Update by pk
* ------------------------------------------------------------- */
UPDATE
<% GenerateTableName(true, 3); %>
SET
<% GenerateUpdates(FilterExcludedUpdateColumns(this.SourceTable.NonPrimaryKeyColumns), 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Update All Procedures
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeUpdateAll)
{
procedureName = GetUpdateAllProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true, false); %>
-- columns
<% GenerateParameters(FilterExcludedUpdateColumns(this.SourceTable.NonPrimaryKeyColumns), 1, true, true); %>
<%
foreach(TableKeySchema keySchema in this.SourceTable.PrimaryKeys)
{
if (IsRelationOneToOne(keySchema))
{
Response.Write("\t-- 1-1 mapped columns for " + keySchema.ForeignKeyTable.Name + "\n");
string prefix = keySchema.ForeignKeyTable.Name + "_";
GenerateParametersWithPrefix(prefix, FilterExcludedUpdateColumns(keySchema.ForeignKeyTable.NonKeyColumns), 1, true, true);
Response.Write("\n");
}
}
%>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Update by pk
* ------------------------------------------------------------- */
UPDATE
<% GenerateTableName(true, 3); %>
SET
<% GenerateUpdates(FilterExcludedUpdateColumns(this.SourceTable.NonPrimaryKeyColumns), 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
-------------------------------------------------------------------------
<%
foreach(TableKeySchema keySchema in this.SourceTable.PrimaryKeys)
{
if (IsRelationOneToOne(keySchema))
{
string prefix = keySchema.ForeignKeyTable.Name + "_";
%>
/* -----------------------------------------------------------------------
* DML Update 1-1 mapped columns for <%= keySchema.ForeignKeyTable.Name %>
* ----------------------------------------------------------------------- */
UPDATE
<%= GetTableOwner() %>[<%= keySchema.ForeignKeyTable.Name %>]
SET
<% GenerateUpdatesWithPrefix(prefix, FilterExcludedUpdateColumns(keySchema.ForeignKeyTable.NonPrimaryKeyColumns), 3); %>
WHERE
<% GenerateConditions(keySchema.ForeignKeyTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when inserting 1-1 mapped info to <%= keySchema.ForeignKeyTable.Name %>.', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>'' when inserting 1-1 mapped info to <%= keySchema.ForeignKeyTable.Name %>.', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
<%
}
}
%>
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Update By Unique Index
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeUpdateByUniqueIndex && hasUniqueIndexes)
{
IndexSchemaCollection indexSchemas = uniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetUpdateByUniqueIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- index
<% GenerateParameters(columns, 1, true); %>
-- columns
<% GenerateParametersForUpdateColumns(columns, FilterExcludedUpdateColumns(this.SourceTable.NonPrimaryKeyColumns), this.NewColumnPrefix, 1); %>,
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Update by unique index
* ------------------------------------------------------------- */
UPDATE
<% GenerateTableName(true, 3); %>
SET
<% GenerateUpdates(columns, FilterExcludedUpdateColumns(this.SourceTable.NonPrimaryKeyColumns), this.NewColumnPrefix, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* Update Bit Procedures
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeUpdateBitColumns && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetUpdateBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true, false); %>
-- optional bits
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
<%
if (columns.Count == 1)
{//single columns only - dont have optional parameters otherwise have an empty case for 0.
%>
/* -------------------------------------------------------------
* Check not already exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return record not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* DML Update bits by pk
* ------------------------------------------------------------- */
UPDATE
<% GenerateTableName(true, 3); %>
SET
<% GenerateUpdate(columns[0], 3, true, true); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
<%
}
else
{
%>
BEGIN
<%
int val = 0;
GenerateUpdateConditionalStatements(columns, 0, 2, ref val, procedureName);
}
%>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end bit check
}
%>
<%------------------------------------------------------------------------------------------
*
* Set Nullable Date Column Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSetNullableDateColumns)
{
ColumnSchemaCollection columns = nullableDateColumns;
if (null != columns && columns.Count > 0)
{
for(int i = 0; i < columns.Count; i++)
{
procedureName = GetSetNullableDateColumnProcedureName(columns[i]);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true, false); %>
-- new date value (is overriden to db current datetime when @UseCurrentDate is set to true)
@<%= StringUtil.ToPascalCase(columns[i].Name) %> datetime = GETDATE OUTPUT,
-- use current datetime value.
@UseCurrentDateTime bit = 1,
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Set Current Date (if required)
* ------------------------------------------------------------- */
IF (@UseCurrentDateTime = 1)
BEGIN
SET @<%= StringUtil.ToPascalCase(columns[i].Name) %> = GETDATE()
END
/* -------------------------------------------------------------
* DML Update date column by pk
* ------------------------------------------------------------- */
BEGIN
UPDATE
<% GenerateTableName(true, 3); %>
SET
<% GenerateUpdate(columns[i], 3, true, true); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
}//if
}//for
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Delete All Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeDeleteAll)
{
procedureName = GetDeleteAllProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
<%
foreach(TableKeySchema tableKeys in this.SourceTable.PrimaryKeys)
{
//get foreign table that maps relationship to current table.
TableSchema fkTable = tableKeys.ForeignKeyTable;
//get the foreign key that maps to table.
foreach(ColumnSchema column in fkTable.ForeignKeyColumns)
{
if (column.IsForeignKeyMember && column.AllowDBNull && tableKeys.ForeignKeyMemberColumns[0].Name == column.Name)
{
%>
/* -------------------------------------------------------------
* DML Delete referenced keys - from <%= fkTable.Name %>
* ------------------------------------------------------------- */
DELETE
<% GenerateTableName(fkTable, true, 3); %>
FROM
<% GenerateTableName(fkTable, true, 3); %>
<% GenerateDeleteReferenceKeyJoinStatements(fkTable, this.SourceTable, 3, false); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when deleting referenced keys from <%= fkTable.Name %>', 10, 1)
RETURN @ErrStatus
END
<%
}
}
}
%>
/* -------------------------------------------------------------
* DML Delete all
* ------------------------------------------------------------- */
DELETE FROM
<% GenerateTableName(true, 3); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected < 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Delete Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeDelete)
{
procedureName = GetDeleteProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
<%
foreach(TableKeySchema tableKeys in this.SourceTable.PrimaryKeys)
{
//get foreign table that maps relationship to current table.
TableSchema fkTable = tableKeys.ForeignKeyTable;
//get the foreign key that maps to table.
foreach(ColumnSchema column in fkTable.ForeignKeyColumns)
{
if (column.IsForeignKeyMember && column.AllowDBNull && tableKeys.ForeignKeyMemberColumns[0].Name == column.Name)
{
%>
/* -------------------------------------------------------------
* DML Delete referenced keys - from <%= fkTable.Name %>
* ------------------------------------------------------------- */
DELETE
<% GenerateTableName(fkTable, true, 3); %>
FROM
<% GenerateTableName(fkTable, true, 3); %>
<% GenerateDeleteReferenceKeyJoinStatements(fkTable, this.SourceTable, 3, false); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when deleting referenced keys from <%= fkTable.Name %>', 10, 1)
RETURN @ErrStatus
END
<%
}
}
}
%>
/* -------------------------------------------------------------
* DML Delete by pk
* ------------------------------------------------------------- */
DELETE FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Delete By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeDeleteByForeignKey && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetDeleteByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- optional keys
<% GenerateOptionalParameters(columns, 1, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Ensure optional parameters provided
* ------------------------------------------------------------- */
IF
(
<% GenerateOptionalConditionNullChecks(columns, 2, "AND"); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Must provide at least one optional parameter for ''<%= procedureName %>''', 15, 1)
RETURN -201 -- expecting parameter code!
END
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
<%
foreach(TableKeySchema tableKeys in this.SourceTable.PrimaryKeys)
{
//get foreign table that maps relationship to current table.
TableSchema fkTable = tableKeys.ForeignKeyTable;
//get the foreign key that maps to table.
foreach(ColumnSchema column in fkTable.ForeignKeyColumns)
{
if (column.IsForeignKeyMember && column.AllowDBNull && tableKeys.ForeignKeyMemberColumns[0].Name == column.Name)
{
%>
/* -------------------------------------------------------------
* DML Delete referenced keys - from <%= fkTable.Name %>
* ------------------------------------------------------------- */
DELETE
<% GenerateTableName(fkTable, true, 3); %>
FROM
<% GenerateTableName(fkTable, true, 3); %>
<% GenerateDeleteReferenceKeyJoinStatements(fkTable, this.SourceTable, 3, false); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when deleting referenced keys from <%= fkTable.Name %>', 10, 1)
RETURN @ErrStatus
END
<%
}
}
}
%>
/* -------------------------------------------------------------
* DML Delete by fk.
* ------------------------------------------------------------- */
DELETE FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Delete By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeDeleteByBitColumn && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetDeleteByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- optional bits
<% GenerateOptionalParameters(columns, 1, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Ensure optional parameters provided
* ------------------------------------------------------------- */
IF
(
<% GenerateOptionalConditionNullChecks(columns, 2, "AND"); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Must provide at least one optional parameter for ''<%= procedureName %>''', 15, 1)
RETURN -201 -- expecting parameter code!
END
/* -------------------------------------------------------------
* Check exists
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
<%
foreach(TableKeySchema tableKeys in this.SourceTable.PrimaryKeys)
{
//get foreign table that maps relationship to current table.
TableSchema fkTable = tableKeys.ForeignKeyTable;
//get the foreign key that maps to table.
foreach(ColumnSchema column in fkTable.ForeignKeyColumns)
{
if (column.IsForeignKeyMember && column.AllowDBNull && tableKeys.ForeignKeyMemberColumns[0].Name == column.Name)
{
%>
/* -------------------------------------------------------------
* DML Delete referenced keys - from <%= fkTable.Name %>
* ------------------------------------------------------------- */
DELETE
<% GenerateTableName(fkTable, true, 3); %>
FROM
<% GenerateTableName(fkTable, true, 3); %>
<% GenerateDeleteReferenceKeyJoinStatements(fkTable, this.SourceTable, 3, false); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when deleting referenced keys from <%= fkTable.Name %>', 10, 1)
RETURN @ErrStatus
END
<%
}
}
}
%>
/* -------------------------------------------------------------
* DML Delete by bits
* ------------------------------------------------------------- */
DELETE FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Delete By Index Procedure
------------------------------------------------------------------------------------------%>
<%
//if (this.IncludeDeleteByIndex && hasNonUniqueIndexes)
if (false)
{
IndexSchemaCollection indexSchemas = nonUniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetDeleteByIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- index
<% GenerateParameters(columns, 1, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
<%
foreach(TableKeySchema tableKeys in this.SourceTable.PrimaryKeys)
{
//get foreign table that maps relationship to current table.
TableSchema fkTable = tableKeys.ForeignKeyTable;
//get the foreign key that maps to table.
foreach(ColumnSchema column in fkTable.ForeignKeyColumns)
{
if (column.IsForeignKeyMember && column.AllowDBNull && tableKeys.ForeignKeyMemberColumns[0].Name == column.Name)
{
%>
/* -------------------------------------------------------------
* DML Delete referenced keys - from <%= fkTable.Name %>
* ------------------------------------------------------------- */
DELETE
<% GenerateTableName(fkTable, true, 3); %>
FROM
<% GenerateTableName(fkTable, true, 3); %>
<% GenerateDeleteReferenceKeyJoinStatements(fkTable, this.SourceTable, 3, false); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when deleting referenced keys from <%= fkTable.Name %>', 10, 1)
RETURN @ErrStatus
END
<%
}
}
}
%>
/* -------------------------------------------------------------
* DML Delete by index
* ------------------------------------------------------------- */
DELETE FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1--is unique!
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* Delete By Unique Index Procedure
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeDeleteByUniqueIndex && hasUniqueIndexes)
{
for(int i = 0; i < uniqueIndexes.Count; i++)
{
ColumnSchemaCollection columns = uniqueIndexes[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetDeleteByUniqueIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- unique indexes
<% GenerateParameters(columns, 1, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Check exists
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
<%
foreach(TableKeySchema tableKeys in this.SourceTable.PrimaryKeys)
{
//get foreign table that maps relationship to current table.
TableSchema fkTable = tableKeys.ForeignKeyTable;
//get the foreign key that maps to table.
foreach(ColumnSchema column in fkTable.ForeignKeyColumns)
{
if (column.IsForeignKeyMember && column.AllowDBNull && tableKeys.ForeignKeyMemberColumns[0].Name == column.Name)
{
%>
/* -------------------------------------------------------------
* DML Delete referenced keys - from <%= fkTable.Name %>
* ------------------------------------------------------------- */
DELETE
<% GenerateTableName(fkTable, true, 3); %>
FROM
<% GenerateTableName(fkTable, true, 3); %>
<% GenerateDeleteReferenceKeyJoinStatements(fkTable, this.SourceTable, 3, false); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when deleting referenced keys from <%= fkTable.Name %>', 10, 1)
RETURN @ErrStatus
END
<%
}
}
}
%>
/* -------------------------------------------------------------
* Delete by unique index
* ------------------------------------------------------------- */
DELETE FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1 --is unique!
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- commit transaction
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* Delete By Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeDeleteBy && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetDeleteByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- optional keys, bits
<% GenerateOptionalParameters(columns, 1, true); %>
-- rows affected
@RowsAffected int = 0 OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
-- begin transaction
BEGIN TRANSACTION
-- system function stores
DECLARE
@ErrStatus int -- stores error status
/* -------------------------------------------------------------
* Ensure optional parameters provided
* ------------------------------------------------------------- */
IF
(
<% GenerateOptionalConditionNullChecks(columns, 2, "AND"); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Must provide at least one optional parameter for ''<%= procedureName %>''', 15, 1)
RETURN -201 -- expecting parameter code!
END
/* -------------------------------------------------------------
* Check exists
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
)
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
<%
foreach(TableKeySchema tableKeys in this.SourceTable.PrimaryKeys)
{
//get foreign table that maps relationship to current table.
TableSchema fkTable = tableKeys.ForeignKeyTable;
//get the foreign key that maps to table.
foreach(ColumnSchema column in fkTable.ForeignKeyColumns)
{
if (column.IsForeignKeyMember && column.AllowDBNull && tableKeys.ForeignKeyMemberColumns[0].Name == column.Name)
{
%>
/* -------------------------------------------------------------
* DML Delete referenced keys - from <%= fkTable.Name %>
* ------------------------------------------------------------- */
DELETE
<% GenerateTableName(fkTable, true, 3); %>
FROM
<% GenerateTableName(fkTable, true, 3); %>
<% GenerateDeleteReferenceKeyJoinStatements(fkTable, this.SourceTable, 3, false); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when deleting referenced keys from <%= fkTable.Name %>', 10, 1)
RETURN @ErrStatus
END
<%
}
}
}
%>
/* -------------------------------------------------------------
* Delete by keys, bits
* ------------------------------------------------------------- */
DELETE FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- commit transaction.
COMMIT TRANSACTION
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelect)
{
procedureName = GetSelectProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true, true); %>
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by pk
* ------------------------------------------------------------- */
SELECT
<% this.GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner, true, true); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
<% //GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Using Out Parameters Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectUsingOutParameters)
{
procedureName = GetSelectUsingOutParametersProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true); %>
-- output parameters
<%
bool includeTrailingComma = true;
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(this.SourceTable.NonPrimaryKeyColumns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateParameter(filteredColumns[i], 1, i == 0, i == filteredColumns.Count - 1 && !includeTrailingComma, true, true);
}
%>
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by key - set output params.
* ------------------------------------------------------------- */
SELECT
<%
for (int i = 0; i < filteredColumns.Count; i++)
{
WriteIndented("@" + filteredColumns[i].Name + " = ", 3);
GenerateColumn(filteredColumns[i], 0, i == 0, i == filteredColumns.Count - 1, includeTableOwner, true, false);
}
%>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
<% //GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select All Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectAll)
{
procedureName = GetSelectAllProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
<% GenerateSortParameters(1, true); %>
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select All
* ------------------------------------------------------------- */
SELECT
<%
//(columns, indentLevel, includeTableOwner, showKeyMarkers, includeForeignKeyNameCandidate, includeTrailingComma)
GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner, true, true, false);
%>
<% //GenerateSelectSortCaseStatements(sortableColumns, 3); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectByForeignKey && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by fk
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
--IF @RowsAffected <> 1
--BEGIN
-- RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
-- RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
--END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectByBitColumn && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by bits
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
--IF @RowsAffected <> 1
--BEGIN
-- RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
-- RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
--END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select By Index Procedure
*
------------------------------------------------------------------------------------------%>
<%
//if (this.IncludeSelectByIndex && hasNonUniqueIndexes)
if (false)
{
IndexSchemaCollection indexSchemas = nonUniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectByIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- index column(s)
<% GenerateParameters(columns, 1, true); %>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
/* -------------------------------------------------------------
* DML Statement
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* Select by index
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected < 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* Select By Unique Index Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectByUniqueIndex && hasUniqueIndexes)
{
IndexSchemaCollection indexSchemas = uniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectByUniqueIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(columns, 1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
/* -------------------------------------------------------------
* DML Statement
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* Select by unique index
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
<% //GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected < 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* Select By Procedure - select by foreign key, index and/or Bits
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectBy && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- foreign key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by keys, bits
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Unique Index By Primary Key
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectUniqueIndexByPrimaryKey && hasUniqueIndexes)
{
IndexSchemaCollection indexSchemas = uniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectUniqueIndexByPrimaryKeyProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- primary key(s)
<% GenerateParameters(this.SourceTable.PrimaryKey.MemberColumns, 1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
/* -------------------------------------------------------------
* DML Statement
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* Select unique index by pk
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(columns, 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
<% //GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Primary Key By Unique Index
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPrimaryKeyByUniqueIndex && hasUniqueIndexes)
{
IndexSchemaCollection indexSchemas = uniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPrimaryKeyByUniqueIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- unique index
<% GenerateParameters(columns, 1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
/* -------------------------------------------------------------
* Check unique index exists
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- return not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* Select pk by unique index
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
<% //GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search All Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchAll)
{
procedureName = GetSelectSearchAllProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
<% GenerateSortParameters(1, true); %>
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select Search All
* ------------------------------------------------------------- */
SELECT
<%
//(columns, indentLevel, includeTableOwner, showKeyMarkers, includeForeignKeyNameCandidate, includeTrailingComma)
GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner, true, true, false);
%>
<% //GenerateSelectSortCaseStatements(sortableColumns, 3); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %><% if (hasSearchableColumns) { %>
WHERE
<% GenerateLikeConditions(searchableColumns, 3, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchByForeignKey && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select Search by fk
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
--IF @RowsAffected <> 1
--BEGIN
-- RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
-- RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
--END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchByBitColumn && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select Search by bits
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
--IF @RowsAffected <> 1
--BEGIN
-- RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
-- RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
--END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search By Procedure - select search by foreign key, index and/or Bits
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchBy && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- foreign key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select Search by keys, bits
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectUsingRowCount)
{
procedureName = GetSelectRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select all - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select RowCount By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectByForeignKeyUsingRowCount && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRowCountByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by key - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select RowCount By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectByBitColumnUsingRowCount && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRowCountByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select RowCount By Index Procedure
*
------------------------------------------------------------------------------------------%>
<%
//if (this.IncludeSelectByIndexUsingRowCount && hasNonUniqueIndexes)
if (false)
{
IndexSchemaCollection indexSchemas = nonUniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRowCountByIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- index column(s)
<% GenerateParameters(columns, 1, true); %>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by index - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select RowCount By Procedure - select by foreign key, index and/or Bits
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectByUsingRowCount && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRowCountByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by keys, bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchUsingRowCount)
{
procedureName = GetSelectSearchRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select all - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %><% if (hasSearchableColumns){ %>
WHERE
<% GenerateLikeConditions(searchableColumns, 3, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search RowCount By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchByForeignKeyUsingRowCount && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchRowCountByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by key - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search RowCount By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchByBitColumnUsingRowCount && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchRowCountByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- search text
@SearchText varchar(50) ,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search RowCount By Procedure - select by foreign key, index and/or Bits
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchByUsingRowCount && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchRowCountByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- search text
@SearchText varchar(50) ,
-- key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select by keys, bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateOrderByClause(sortableColumns, 2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectList && hasNameTitleColumnCandidate)
{
procedureName = GetSelectListProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectListByForeignKey && hasNameTitleColumnCandidate && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectListByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by fk
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Index Procedure
*
------------------------------------------------------------------------------------------%>
<%
//if (this.IncludeSelectListByIndex && hasNameTitleColumnCandidate && hasNonUniqueIndexes)
if (false)
{
IndexSchemaCollection indexSchemas = nonUniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectListByIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- index column(s)
<% GenerateParameters(columns, 1, true); %>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by index
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectListByBitColumn && hasNameTitleColumnCandidate && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectListByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by bits
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectListBy && hasNameTitleColumnCandidate && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectListByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- foreign key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by keyts, bits
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectListUsingRowCount && hasNameTitleColumnCandidate)
{
procedureName = GetSelectListUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Foreign Key Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectListByForeignKeyUsingRowCount && hasNameTitleColumnCandidate && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectListByForeignKeyUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %>,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by fk - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Index Procedure
*
------------------------------------------------------------------------------------------%>
<%
//if (this.IncludeSelectListByIndexUsingRowCount && hasNameTitleColumnCandidate && hasNonUniqueIndexes)
if (false)
{
IndexSchemaCollection indexSchemas = nonUniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectListByIndexUsingRowCountProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %>,
-- index column(s)
<% GenerateParameters(columns, 1, true); %>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by index - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectListByBitColumnUsingRowCount && hasNameTitleColumnCandidate && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectListByBitColumnUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %>,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectListByUsingRowCount && hasNameTitleColumnCandidate && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectListByUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %>,
-- foreign key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by keys, bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search List Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchList && hasNameTitleColumnCandidate)
{
procedureName = GetSelectSearchListProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %><% if (hasSearchableColumns){ %>
WHERE
<% GenerateLikeConditions(searchableColumns, 3, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search List By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchListByForeignKey && hasNameTitleColumnCandidate && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchListByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by fk
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select List By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchListByBitColumn && hasNameTitleColumnCandidate && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchListByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by bits
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search List By Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchListBy && hasNameTitleColumnCandidate && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchListByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- foreign key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by keyts, bits
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search List Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchListUsingRowCount && hasNameTitleColumnCandidate)
{
procedureName = GetSelectSearchListUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %> ,
-- search text
@SearchText varchar(50) ,
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %><% if (hasSearchableColumns){ %>
WHERE
<% GenerateLikeConditions(searchableColumns, 3, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search List By Foreign Key Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchListByForeignKeyUsingRowCount && hasNameTitleColumnCandidate && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchListByForeignKeyUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %>,
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by fk - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search List By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchListByBitColumnUsingRowCount && hasNameTitleColumnCandidate && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchListByBitColumnUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %>,
-- search text
@SearchText varchar(50) ,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search List By Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchListByUsingRowCount && hasNameTitleColumnCandidate && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchListByUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of rows to return
@RowCount int = <%= DefaultRowCount %>,
-- search text
@SearchText varchar(50) ,
-- foreign key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select list by keys, bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateConcatenatedColumns(this.SourceTable.PrimaryKey.MemberColumns, 0, includeTableOwner); %> AS [DataValueField],
<% GenerateColumn(nameTitleCandidateColumn, 3, false, true, includeTableOwner, false, false, false, false, "DataTextField"); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
<% GenerateListOrderByClause(2); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandom)
{
procedureName = GetSelectRandomProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select top random
* ------------------------------------------------------------- */
SELECT TOP 1
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 1); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random Primary Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandomPrimaryKey)
{
procedureName = GetSelectRandomPrimaryKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select top pk
* ------------------------------------------------------------- */
SELECT TOP 1
<% GenerateColumns(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random Primary Key Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandomPrimaryKeyUsingRowCount)
{
procedureName = GetSelectRandomPrimaryKeyUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
@RowCount int = <%= DefaultRowCount %>,
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random pk - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(this.SourceTable.PrimaryKey.MemberColumns, 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random Unique Index Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandomUniqueIndex && hasUniqueIndexes)
{
IndexSchemaCollection indexSchemas = uniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRandomUniqueIndexProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
/* -------------------------------------------------------------
* Check records
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- records not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* Select random unique index - using specified rowcount
* ------------------------------------------------------------- */
SELECT TOP 1
<% GenerateColumns(FilterExcludedColumns(columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
--IF @RowsAffected < 1
--BEGIN
-- RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
-- RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
--END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random Unique Index Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandomUniqueIndexUsingRowCount && hasUniqueIndexes)
{
IndexSchemaCollection indexSchemas = uniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRandomUniqueIndexUsingRowCountProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
@RowCount int = <%= DefaultRowCount %>,
-- unique index
<% GenerateParameters(columns, 1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
/* -------------------------------------------------------------
* Check records exist.
* ------------------------------------------------------------- */
IF NOT EXISTS
(
SELECT
NULL
FROM
<% GenerateTableName(true, 3); %>
)
BEGIN
-- rollback transaction
IF @@TRANCOUNT <> 0
ROLLBACK TRANSACTION
RETURN -1 -- records not found
END
ELSE
BEGIN
/* -------------------------------------------------------------
* Select random unique index - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
--IF @RowsAffected < 1
--BEGIN
-- RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
-- RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
--END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}//end if
}//end for
}
%>
<%------------------------------------------------------------------------------------------
*
* - Select Random By Foreign Key Procedure
* - Select Random By Index Procedure
* - Select Random By Bit Procedure
* - Select Random By Procedure
* All the above procedures can be handled by the Random RowCount ones below.
*
------------------------------------------------------------------------------------------%>
<%------------------------------------------------------------------------------------------
*
* Select Random Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandomUsingRowCount)
{
procedureName = GetSelectRandomUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random By Foreign Key Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandomByForeignKeyUsingRowCount && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRandomByForeignKeyUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random by fk - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random By Index Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
//if (this.IncludeSelectRandomByIndexUsingRowCount && hasNonUniqueIndexes)
if (false)
{
IndexSchemaCollection indexSchemas = nonUniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRandomByIndexUsingRowCountProcedureName(columns);
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- index
<% GenerateParameters(columns, 1, true); %>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random by index - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateConditions(columns, 3, includeTableOwner); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random By Bit Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandomByBitColumnUsingRowCount && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRandomByBitColumnUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random by bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Random By Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectRandomByUsingRowCount && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectRandomByUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random by keys, bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search Random Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchRandom)
{
procedureName = GetSelectSearchRandomProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select top random
* ------------------------------------------------------------- */
SELECT TOP 1
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %><% if (hasSearchableColumns){ %>
WHERE
<% GenerateLikeConditions(searchableColumns, 3, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 1); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected <> 1
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search Random Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchRandomUsingRowCount)
{
procedureName = GetSelectSearchRandomUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- search text
@SearchText varchar(50) ,
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %><% if (hasSearchableColumns){ %>
WHERE
<% GenerateLikeConditions(searchableColumns, 3, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- set row count
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search Random By Foreign Key Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchRandomByForeignKeyUsingRowCount && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchRandomByForeignKeyUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random by fk - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search Random By Bit Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchRandomByBitColumnUsingRowCount && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchRandomByBitColumnUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random by bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Search Random By Using RowCount Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectSearchRandomByUsingRowCount && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectSearchRandomByUsingRowCountProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- number of records
@RowCount int = <%= DefaultRowCount %>,
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
<% GenerateItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
-- set row count
<% GenerateRowCountStatement("@RowCount", 1); %>
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select random by keys, bits - using specified rowcount
* ------------------------------------------------------------- */
SELECT
<% GenerateColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, includeTableOwner); %>
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
ORDER BY
NEWID()
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @RowCount
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn row count off
<% GenerateRowCountStatement("0", 1); %>
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPaged)
{
procedureName = GetSelectPagedProcedureName();
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true, false); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountAllProcedureName() %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPagedByForeignKey && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPagedByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true, false); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
WHERE
<% GenerateOptionalConditions(columns, 4, includeTableOwner); %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountByForeignKeyProcedureName() %>
<% this.GenerateExecuteParameters(columns, 8, true); %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPagedByBitColumn && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPagedByBitColumnProcedureName();
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true, false); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
WHERE
<% GenerateOptionalConditions(columns, 4, includeTableOwner); %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountByBitColumnProcedureName() %>
<% this.GenerateExecuteParameters(columns, 8, true); %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged By Index Procedure
*
------------------------------------------------------------------------------------------%>
<%
//if (this.IncludeSelectPagedByIndex && hasNonUniqueIndexes)
if (false)
{
IndexSchemaCollection indexSchemas = nonUniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
//These are NOT conditional columns!!!!
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPagedByIndexProcedureName(columns);
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
-- index column(s)
<% GenerateParameters(columns, 1, true); %>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set by index
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountByForeignKeyProcedureName() %>
<% this.GenerateExecuteParameters(columns, 8, true); %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged By Procedure - select by foreign key, index and/or Bits
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPagedBy && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPagedByProcedureName();
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true, false); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
WHERE
<% GenerateOptionalConditions(columns, 4, includeTableOwner); %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountByProcedureName() %>
<% this.GenerateExecuteParameters(columns, 8, true); %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged Search Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPagedSearch && !isMappingTable)
{
procedureName = GetSelectPagedSearchProcedureName();
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
@SearchText varchar(50) ,
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set using search keywords
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %><% if (hasSearchableColumns) { %>
WHERE
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountSearchProcedureName() %>
@SearchText = @SearchText,
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select PagedSearch By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPagedSearchByForeignKey && hasForeignKeys && !isMappingTable)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPagedSearchByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set using search keywords
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
WHERE
<% GenerateOptionalConditions(columns, 4, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 5, includeTableOwner, "OR", "@SearchText"); %>
)<% }//end if hasSearchableColumns %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountSearchByForeignKeyProcedureName() %>
@SearchText = @SearchText,
<% this.GenerateExecuteParameters(columns, 8, true); %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged Search By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPagedSearchByBitColumn && hasBits && !isMappingTable)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPagedSearchByBitColumnProcedureName();
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
@SearchText varchar(50) ,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set using search keywords
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
WHERE
<% GenerateOptionalConditions(columns, 4, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 5, includeTableOwner, "OR", "@SearchText"); %><% }//end if hasSearchableColumns %>
)
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountSearchByBitColumnProcedureName() %>
@SearchText = @SearchText,
<% this.GenerateExecuteParameters(columns, 8, true); %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged Search By Index Procedure
*
------------------------------------------------------------------------------------------%>
<%
//if (this.IncludeSelectPagedSearchByIndex && hasNonUniqueIndexes && !isMappingTable)
if (false)
{
IndexSchemaCollection indexSchemas = nonUniqueIndexes;
for(int i = 0; i < indexSchemas.Count; i++)
{
ColumnSchemaCollection columns = indexSchemas[i].MemberColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPagedSearchByIndexProcedureName(columns);
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
@SearchText varchar(50) ,
-- index column(s)
<% GenerateParameters(columns, 1, true); %>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set by index - using specified keywords
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
WHERE
<% GenerateConditions(columns, 4, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(FilterNonTextualColumns(this.SourceTable.Columns), 5, includeTableOwner, "OR", "@SearchText"); %>
)<% } //hasSearchableColumns %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountByForeignKeyProcedureName() %>
@SearchText = @SearchText,
<% this.GenerateExecuteParameters(columns, 8, true); %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Paged Search By Procedure - select by foreign key, index and/or Bits
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectPagedSearchBy && hasKeyAndBitColumns && !isMappingTable)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectPagedSearchByProcedureName();
GenerateProcedureHeader(procedureName, "'Custom Paging in ASP.NET 2.0 with SQL Server 2005' - http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/031506-1.aspx");
%>
CREATE PROCEDURE <%= procedureName %>
-- paging parameters
@PageNumber int = <%= DefaultPageNumber %>,
@PageSize int = <%= DefaultPageSize %>,
@SearchText varchar(50) ,
-- foreign key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- sort expressions
<% GenerateSortParameters(1, true); %>
-- item count
<% GenerateVirtualItemCountParameters(1, false); %>
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
-- parameter validation
IF (@PageNumber < 1) SET @PageNumber = <%= DefaultPageNumber %>
IF (@PageSize < 1) SET @PageSize = <%= DefaultPageSize %>
/* -------------------------------------------------------------
* Determine start and end row index.
* ------------------------------------------------------------- */
DECLARE
@StartRowNum int, -- the starting row number
@EndRowNum int -- the ending row number
SELECT
@StartRowNum = ((@PageNumber-1) * @PageSize)+1,
@EndRowNum = (@StartRowNum + @PageSize)-1
BEGIN
/* -------------------------------------------------------------
* Select paged set using search keywords
* ------------------------------------------------------------- */
SELECT
[RowNum],
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 3, false, true, false, true); %>
FROM
(
SELECT
<% GeneratePagedColumns(FilterExcludedColumns(this.SourceTable.Columns), 4, includeTableOwner, false, true); %>
ROW_NUMBER() OVER
(
<% GenerateOrderByClause(sortableColumns, 5); %>
) AS [RowNum]
FROM
<% GenerateTableName(true, 4); %>
<% GenerateJoinStatements(SourceTable, 4); %>
WHERE
<% GenerateOptionalConditions(columns, 4, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 5, includeTableOwner, "OR", "@SearchText"); %>
)<% }//end if hasSearchableColumns %>
) AS [PagedSet]
WHERE
[RowNum] BETWEEN @StartRowNum AND @EndRowNum
<% GenerateForXmlClause(ForXml, 3); %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
-- ensure correct number of rows affected
IF @RowsAffected > @PageSize
BEGIN
RAISERROR('Unexpected number of rows affected by stored procedure ''<%= procedureName %>''', 10, 1)
RETURN -999 -- standardised return code for this - 'Unexpected rowcount'
END
/* -------------------------------------------------------------
* Total Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValue int
EXEC @ReturnValue = <%= this.GetSelectCountAllProcedureName() %> @ItemCount = @ItemCount OUTPUT
IF (@ReturnValue <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ReturnValue
END
<% }else{ %>
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the total item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
/* -------------------------------------------------------------
* Virtual Item Count
* ------------------------------------------------------------- */
IF (@IncludeItemCount = 1)
BEGIN
<% if (this.IncludeSelectCountAll || this.UseSelectCountAllProcedure) { %>
DECLARE @ReturnValueVirtual int
EXEC @ReturnValueVirtual = <%= this.GetSelectCountSearchByProcedureName() %>
@SearchText = @SearchText,
<% this.GenerateExecuteParameters(columns, 8, true); %>
@ItemCount = @VirtualItemCount OUTPUT
IF (@ReturnValueVirtual <> 0)
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' determining the virtual item count.', 10, 1)
RETURN @ReturnValueVirtual
END
<% }else{ %>
SELECT
@VirtualItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateForXmlClause(ForXml, 2); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>'' when determining the virtual item count.', 10, 1)
RETURN @ErrStatus
END
<%
}//SelectCountAll
%>
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Count All Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectCountAll)
{
procedureName = GetSelectCountAllProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- item count
@ItemCount bigint OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select total count
* ------------------------------------------------------------- */
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Count By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectCountByForeignKey && hasForeignKeys)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectCountByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- foreign key(s)
<% GenerateOptionalParameters(columns, 1, true); %>
-- item count
@ItemCount bigint OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select total count
* ------------------------------------------------------------- */
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Count By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectCountByBitColumn && hasBits)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectCountByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- bit column(s)
<% GenerateOptionalParameters(columns, 1, true); %>
-- item count
@ItemCount bigint OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select total count
* ------------------------------------------------------------- */
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Count By Procedure - select by foreign key, index and/or Bits
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectCountBy && hasKeyAndBitColumns)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectCountByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- foreign key and bit columns
<% GenerateOptionalParameters(columns, 1, true); %>
-- item count
@ItemCount bigint OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select total count
* ------------------------------------------------------------- */
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %>
/* must use single statement immediately to store system functions
as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */
SELECT
@ErrStatus = @@ERROR,
@RowsAffected = @@ROWCOUNT
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Count Search Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectCountSearch && !isMappingTable)
{
procedureName = GetSelectCountSearchProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- item count
@ItemCount bigint OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select total count - using specified keywords
* ------------------------------------------------------------- */
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %><% if (hasSearchableColumns) { %>
WHERE
<% GenerateLikeConditions(searchableColumns, 3, includeTableOwner, "OR", "@SearchText"); %><% } //end if hasSearchableColumns %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Count Search By Foreign Key Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectCountSearchByForeignKey && hasForeignKeys && !isMappingTable)
{
ColumnSchemaCollection columns = fkColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectCountSearchByForeignKeyProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- foreign key(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
@ItemCount bigint OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select total count - using specified keywords
* ------------------------------------------------------------- */
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %>
)<% } //end if hasSearchableColumns %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Count Search By Bit Procedure
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectCountSearchByBitColumn && hasBits && !isMappingTable)
{
ColumnSchemaCollection columns = bitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectCountSearchByBitColumnProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- bit column(s)
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
@ItemCount bigint OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select total count - using specified keywords
* ------------------------------------------------------------- */
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %>
)<% } //end if hasSearchableColumns %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<%------------------------------------------------------------------------------------------
*
* Select Count Search By Procedure - select by foreign key, index and/or Bits
*
------------------------------------------------------------------------------------------%>
<%
if (this.IncludeSelectCountSearchBy && hasKeyAndBitColumns && !isMappingTable)
{
ColumnSchemaCollection columns = keyAndBitColumns;
if (null != columns && columns.Count > 0)
{
procedureName = GetSelectCountSearchByProcedureName();
GenerateProcedureHeader(procedureName);
%>
CREATE PROCEDURE <%= procedureName %>
-- search text
@SearchText varchar(50) ,
-- foreign key, index and bit columns
<% if (columns.Count == 1)
GenerateParameters(columns, 1, true);
else
GenerateOptionalParameters(columns, 1, true);
%>
-- item count
@ItemCount bigint OUTPUT
AS
-- turn off rows affected
SET NOCOUNT ON
--isolation level
<% GenerateSetTransactionIsolationLevelStatement(IsolationLevel, 1); %>
-- system function stores
DECLARE
@ErrStatus int, -- stores error status
@RowsAffected int -- stores number of rows affected
BEGIN
/* -------------------------------------------------------------
* Select total count - using specified keywords
* ------------------------------------------------------------- */
SELECT
@ItemCount = ISNULL(COUNT(*),0)
FROM
<% GenerateTableName(true, 3); %>
<% GenerateJoinStatements(SourceTable, 3); %>
WHERE
<% GenerateOptionalConditions(columns, 3, includeTableOwner); %><% if (hasSearchableColumns) { %>
AND
(
<% GenerateLikeConditions(searchableColumns, 4, includeTableOwner, "OR", "@SearchText"); %>
)<% } //end if hasSearchableColumns %>
-- check for errors
IF @ErrStatus <> 0
BEGIN
RAISERROR('Error occurred in stored procedure ''<%= procedureName %>''', 10, 1)
RETURN @ErrStatus
END
END
-- turn on rows affected
SET NOCOUNT OFF
-- success(0)
RETURN 0
<%
GenerateProcedureFooter(procedureName);
this.Progress.PerformStep();
}
}
%>
<script runat="template">
#region Member Variables
private StringCollection _droppedProcedureNames = new StringCollection();
private StringCollection _generatedProcedureNames = new StringCollection();
#endregion
#region Isolation Level
public enum TransactionIsolationLevelEnum
{
ReadCommitted,
ReadUncommitted,
RepeatableRead,
Serializable
}
public void GenerateSetTransactionIsolationLevelStatement(TransactionIsolationLevelEnum isolationLevel, int indentLevel)
{
GenerateIndent(indentLevel);
Response.Write("SET TRANSACTION ISOLATION LEVEL ");
switch (isolationLevel)
{
case TransactionIsolationLevelEnum.ReadUncommitted:
{
Response.WriteLine("READ UNCOMMITTED");
break;
}
case TransactionIsolationLevelEnum.RepeatableRead:
{
Response.WriteLine("REPEATABLE READ");
break;
}
case TransactionIsolationLevelEnum.Serializable:
{
Response.WriteLine("SERIALIZABLE");
break;
}
default:
{
Response.WriteLine("READ COMMITTED");
break;
}
}
}
#endregion
#region For Xml
public enum ForXmlEnum
{
None,
Raw,
Auto,
Explicit
}
public void GenerateForXmlClause(ForXmlEnum forXml, int indentLevel)
{
GenerateIndent(indentLevel) ;
switch (forXml)
{
case ForXmlEnum.Raw:
{
Response.Write("FOR\n");
GenerateIndent(indentLevel+1);
Response.WriteLine("XML RAW");
break;
}
case ForXmlEnum.Auto:
{
Response.Write("FOR\n");
GenerateIndent(indentLevel+1);
Response.WriteLine("XML AUTO");
break;
}
case ForXmlEnum.Explicit:
{
Response.Write("FOR\n");
GenerateIndent(indentLevel+1);
Response.WriteLine("XML EXPLICIT");
break;
}
default:
{
break;
}
}
}
#endregion
#region Helpers
public bool IsJunctionTable(TableSchema table)
{
if (table.PrimaryKey.MemberColumns.Count > 1)
{
foreach(ColumnSchema pkColumn in table.PrimaryKey.MemberColumns)
{
if (!pkColumn.IsForeignKeyMember)
return false;
}
return true;
}
return false;
}
public bool ContainsOneToOneKey(TableSchema table)
{
foreach(TableKeySchema keySchema in table.PrimaryKeys)
{
if (IsRelationOneToOne(keySchema))
return true;
}
return false;
}
public bool IsRelationOneToOne(TableKeySchema keyschema)
{
bool result = true;
// Each member must reference a unique key in the foreign table
foreach(ColumnSchema column in keyschema.ForeignKeyMemberColumns)
{
bool columnIsUnique = false;
// the only way to find the key in the foreign table is to loop through the indexes
foreach(IndexSchema i in keyschema.ForeignKeyTable.Indexes)
{
//The index must be unique and the numer of columns columns
//in the FK must match the number of columns in the index
if ((i.IsUnique || i.IsPrimaryKey) && (keyschema.ForeignKeyMemberColumns.Count == i.MemberColumns.Count))
{
//The index must contain the same column
if (i.MemberColumns.Contains(column.Name) && (!IsJunctionTable(keyschema.ForeignKeyTable)))
{
columnIsUnique = true;
}
}
}
result = result && columnIsUnique;
}
return result;
}
#endregion
#region Code Generation Helpers
public string GetTableOwner()
{
return GetTableOwner(this.SourceTable);
}
public string GetTableOwner(TableSchema table)
{
return GetTableOwner(table, true);
}
public string GetTableOwner(TableSchema table, bool includeDot)
{
if (table.Owner.Length > 0)
{
if (includeDot)
{
return "[" + table.Owner + "].";
}
else
{
return "[" + table.Owner + "]";
}
}
else
{
return "";
}
}
public string GetTableOwner(bool includeDot)
{
if (this.SourceTable.Owner.Length > 0)
{
if (includeDot)
{
return "[" + this.SourceTable.Owner + "].";
}
else
{
return "[" + this.SourceTable.Owner + "]";
}
}
else
{
return "";
}
}
public void GenerateDropStatement(string procedureName)
{
// check to see if this procedure has already been dropped.
if (!_droppedProcedureNames.Contains(procedureName))
{
Response.WriteLine("IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'{0}') AND type in (N'P', N'PC'))", procedureName);
//Response.WriteLine("IF OBJECT_ID(N'{0}') IS NOT NULL", procedureName);
GenerateIndent(1);
Response.WriteLine("DROP PROCEDURE {0}", procedureName);
Response.WriteLine("");
// add this procedure to the List of dropped procedures
_droppedProcedureNames.Add(procedureName);
}
}
public void GenerateProcedureHeader(string procedureName)
{
GenerateProcedureHeader(procedureName, null);
}
public void GenerateProcedureHeader(string procedureName, string comments)
{
Response.WriteLine("--region {0}", procedureName);
Response.WriteLine("");
Response.WriteLine("------------------------------------------------------------------------------------------------------------------------");
Response.WriteLine("-- Procedure Name: {0}", procedureName);
Response.WriteLine("-- Date Generated: {0}", DateTime.Now.ToLongDateString());
Response.WriteLine("-- Author: Stephen McCormack - stephenm@mwebsolutions.com.au");
Response.WriteLine("-- Company: MWeb Solutions Pty Ltd");
Response.WriteLine("-- Software: CodeSmith v{0}", typeof(CodeTemplate).Assembly.GetName().Version.ToString());
Response.WriteLine("-- Template: {0}", this.CodeTemplateInfo.FileName);
if (null != comments && String.Empty != comments)
Response.WriteLine("-- Comments: {0}", comments);
Response.WriteLine("--------- --------------------------------------------------------------------------------------------------------------");
}
public void GenerateProcedureFooter(string procedureName)
{
Response.WriteLine("--endregion");
Response.WriteLine("");
Response.WriteLine("GO");
Response.WriteLine("");
}
public void GenerateIndent(int indentLevel)
{
for (int i = 0; i < indentLevel; i++)
{
Response.Write('\t');
}
}
public void WriteIndented(string s, int indentLevel)
{
if (null != s)
{
GenerateIndent(indentLevel);
Response.Write(s);
}
}
public void WriteIndentedLine(string s, int indentLevel)
{
if (null != s)
{
WriteIndented(s + "\n", indentLevel);
}
}
//------------------------------------------------------------------------------------
// Has Modified Date
//------------------------------------------------------------------------------------
public bool HasColumnName(ColumnSchemaCollection columns, string columnName)
{
bool hasColumnName = false;
for (int i = 0; i < columns.Count; i++)
{
if (!hasColumnName)
{
hasColumnName = (columns[i].Name.ToLower() == columnName.ToLower());
}
if (hasColumnName)
{
break;
}
}
return hasColumnName;
}
//------------------------------------------------------------------------------------
// Generate Parameter
//------------------------------------------------------------------------------------
public void GenerateParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateParameter(column, indentLevel, isFirst, isLast, false, false, null);
}
public void GenerateParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool isOutput)
{
GenerateParameter(column, indentLevel, isFirst, isLast, isOutput, false, null);
}
public void GenerateParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool isOutput, bool includeDefaultValue)
{
GenerateParameter(column, indentLevel, isFirst, isLast, isOutput, includeDefaultValue, null);
}
public void GenerateParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool isOutput, string defaultValue)
{
GenerateParameter(column, indentLevel, isFirst, isLast, isOutput, !string.IsNullOrEmpty(defaultValue), defaultValue);
}
private void GenerateParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool isOutput, bool includeDefaultValue, string defaultValue)
{
GenerateIndent(indentLevel);
Response.Write(this.GetSqlParameterStatement(column, isOutput, includeDefaultValue, defaultValue));
if (!isLast) Response.Write(",");
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
/// <summary>
/// Returns a T-SQL parameter statement based on the given column.
/// </summary>
/// <param name="column"></param>
/// <param name="isOutput"></param>
/// <returns></returns>
public string GetSqlParameterStatement(ColumnSchema column, bool isOutput, bool includeDefaultValue, string defaultValue)
{
string param = "@" + column.Name + " " + column.NativeType;
if (!this.IsUserDefinedType(column))
{
switch (column.DataType)
{
case DbType.Decimal:
{
param += "(" + column.Precision + ", " + column.Scale + ")";
break;
}
case DbType.AnsiString:
case DbType.AnsiStringFixedLength:
case DbType.String:
case DbType.StringFixedLength:
{
if (column.NativeType != "text" && column.NativeType != "ntext")
{
if (column.Size > 0)
{
param += "(" + column.Size + ")";
}
else if (column.Size == -1)
{
param += "(max)";
}
}
break;
}
}
}
if (includeDefaultValue)
{
if (string.IsNullOrEmpty(defaultValue))
{
defaultValue = column.ExtendedProperties["CS_Default"].Value.ToString();
}
if (!string.IsNullOrEmpty(defaultValue))
{
//Debugger.Break();
if (defaultValue.StartsWith("(") && defaultValue.EndsWith(")"))
defaultValue = defaultValue.Substring(1, defaultValue.Length-2); //remove braces.
if (defaultValue.StartsWith("(") && defaultValue.EndsWith(")"))
defaultValue = defaultValue.Substring(1, defaultValue.Length-2); //remove braces.
if (defaultValue.EndsWith("()"))
defaultValue = defaultValue.Substring(0, defaultValue.Length-2); //remove function braces (e.g. getdate()).
param += " = " + defaultValue;
}
}
if (isOutput)
{
param += " OUTPUT";
}
return param;
}
//------------------------------------------------------------------------------------
// Generate Parameters
//------------------------------------------------------------------------------------
public void GenerateParameters(ColumnSchemaCollection columns, int indentLevel)
{
GenerateParameters(columns, indentLevel, false, false);
}
public void GenerateParameters(ColumnSchemaCollection columns, int indentLevel, bool includeTrailingComma)
{
GenerateParameters(columns, indentLevel, includeTrailingComma, false);
}
public void GenerateParameters(ColumnSchemaCollection columns, int indentLevel, bool includeTrailingComma, bool includeDefaultValue)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateParameter(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1 && !includeTrailingComma, false, includeDefaultValue);
}
}
//------------------------------------------------------------------------------------
// Generate Parameters w/ Name Prefix
//------------------------------------------------------------------------------------
public void GenerateParametersWithPrefix(string prefix, ColumnSchemaCollection columns, int indentLevel)
{
GenerateParametersWithPrefix(prefix, columns, indentLevel, false, false);
}
public void GenerateParametersWithPrefix(string prefix, ColumnSchemaCollection columns, int indentLevel, bool includeTrailingComma)
{
GenerateParametersWithPrefix(prefix, columns, indentLevel, includeTrailingComma, false);
}
public void GenerateParametersWithPrefix(string prefix, ColumnSchemaCollection columns, int indentLevel, bool includeTrailingComma, bool includeDefaultValue)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
bool isLast = i == filteredColumns.Count - 1 && !includeTrailingComma;
bool isOutput = false;
GenerateIndent(indentLevel);
Response.Write(this.GetSqlParameterStatement(filteredColumns[i], isOutput, includeDefaultValue, null).Replace("@","@" + prefix));
if (!isLast) Response.Write(",");
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
}
//------------------------------------------------------------------------------------
// Generate Optional Parameter(s)
//------------------------------------------------------------------------------------
public void GenerateOptionalParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool isOutput)
{
GenerateParameter(column,indentLevel,isFirst,isLast,isOutput,"NULL");
}
public void GenerateOptionalParameters(ColumnSchemaCollection columns, int indentLevel, bool includeTrailingComma)
{
//Debugger.Break();
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateOptionalParameter(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1 && !includeTrailingComma, false);
}
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
// Generate Execute Parameter
//------------------------------------------------------------------------------------
public void GenerateExecuteParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateExecuteParameter(column, indentLevel, isFirst, isLast, false);
}
public void GenerateExecuteParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool isOutput)
{
string s = "@" + column.Name + " = " + "@" + column.Name;
if (isOutput) s += " OUTPUT";
WriteIndented(s, indentLevel);
if (!isLast) Response.Write(",");
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
//------------------------------------------------------------------------------------
// Generate execute Parameters
//------------------------------------------------------------------------------------
public void GenerateExecuteParameters(ColumnSchemaCollection columns, int indentLevel)
{
GenerateExecuteParameters(columns, indentLevel, false);
}
public void GenerateExecuteParameters(ColumnSchemaCollection columns, int indentLevel, bool includeTrailingComma)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateExecuteParameter(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1 && !includeTrailingComma, false);
}
}
//------------------------------------------------------------------------------------
// Generate Execute Optional Parameter(s)
//------------------------------------------------------------------------------------
public void GenerateOptionalExecuteParameter(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool isOutput)
{
GenerateExecuteParameter(column,indentLevel,isFirst,isLast,isOutput);
}
public void GenerateOptionalExecuteParameters(ColumnSchemaCollection columns, int indentLevel, bool includeTrailingComma)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateOptionalExecuteParameter(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1 && !includeTrailingComma, false);
}
}
//------------------------------------------------------------------------------------
public void GenerateColumn(ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateColumn(column, indentLevel, isFirst, isLast, false, false);
}
public void GenerateColumn(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner)
{
GenerateColumn(column, indentLevel, isFirst, isLast, includeTableOwner, true, this.IncludeForeignKeyNameCandidate, false, false);
}
public void GenerateColumn(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, bool showKeyMarkers)
{
GenerateColumn(column, indentLevel, isFirst, isLast, includeTableOwner, showKeyMarkers, this.IncludeForeignKeyNameCandidate, false, false );
}
public void GenerateColumn(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, bool showKeyMarkers, bool includeForeignKeyNameCandidate)
{
GenerateColumn(column, indentLevel, isFirst, isLast, includeTableOwner, showKeyMarkers, includeForeignKeyNameCandidate, false, false );
}
public void GenerateColumn(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, bool showKeyMarkers, bool includeForeignKeyNameCandidate, bool isCommented)
{
GenerateColumn(column, indentLevel, isFirst, isLast, includeTableOwner, showKeyMarkers, includeForeignKeyNameCandidate, isCommented, false );
}
public void GenerateColumn(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, bool showKeyMarkers, bool includeForeignKeyNameCandidate, bool isCommented, bool fkAliasOnly)
{
GenerateColumn(column, indentLevel, isFirst, isLast, includeTableOwner, showKeyMarkers, includeForeignKeyNameCandidate, isCommented, fkAliasOnly, null);
}
public void GenerateColumn(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, bool showKeyMarkers, bool includeForeignKeyNameCandidate, bool isCommented, bool fkAliasOnly, string aliasName)
{
//GenerateColumn(nameTitleCandidateColumn, 2, false, true, includeTableOwner, false, false)
GenerateIndent(indentLevel);
if (isCommented)
{
Response.Write("--");
}
if (includeTableOwner)
{
//int keyIndex = 0;
//if (column.IsForeignKeyMember && IsLoopBackKey(column, ref keyIndex))
//{
// Response.Write("[" + column.Table.Name + "_" + keyIndex + "].");
//}
//else
//{
Response.Write(GetTableOwner() + "[" + column.Table.Name + "].");
//}
}
Response.Write("[");
string columnName = column.Name;
Response.Write(columnName);
Response.Write("]");
if (!isLast ||
(isLast && column.IsForeignKeyMember && includeForeignKeyNameCandidate))
{//comma separate if not last or (is last and have to include fk name candidate)!
Response.Write(",");
}
//display key markers
if (showKeyMarkers)
GenerateCommentedKeyMarkers(column);
//generate foreign key name column candidate
if (this.IncludeJoinStatements && includeForeignKeyNameCandidate)
{
//TODO: Removed the !IsPrimaryKeyMember as we still want to retrieve
//the foreign key name/title candidate if the primary key is also a foreign key.
if (/*!column.IsPrimaryKeyMember && */column.IsForeignKeyMember)
{
Response.WriteLine();
GenerateIndent(indentLevel);
//find key index
int keyIndex = 0;
for(int i=0; i < column.Table.ForeignKeys.Count; i++)
{
//TODO: FIX TO HANDLE COMPOSITE KEY!!
if (column.Name == column.Table.ForeignKeys[i].ForeignKeyMemberColumns[0].Name)
{
keyIndex = i;
break;
}
}
//now display key as an aliased column
TableSchema foreignTable = column.Table.ForeignKeys[keyIndex].PrimaryKeyTable;
ColumnSchema candidateColumn = GetNameTitleColumnCandidate(foreignTable);
if (null != candidateColumn)
{
if (isCommented)
{
Response.Write("--");
}
string fkAlias = MakeForeignKeyAlias(column.Name, candidateColumn.Name);
string fkColumnName = String.Empty;
if (fkAliasOnly)
{//required for paged column sets.
fkColumnName = "[" + fkAlias + "]";
}
else
{
int index = 0;
bool isLoopBackKey = IsLoopBackKey(column, ref keyIndex);
if (column.IsForeignKeyMember && isLoopBackKey)
{
fkColumnName = "[" + column.Table.Name + "_" + (index+1).ToString().PadLeft(2, '0') + "].[" + candidateColumn.Name + "] AS [" + fkAlias + "]";
}
else
{
fkColumnName = "[" + candidateColumn.Name + "] AS [" + fkAlias + "]";
if (includeTableOwner)
fkColumnName = GetTableOwner() + "[" + foreignTable.Name + "]." + fkColumnName;
}
}
Response.Write(fkColumnName);
if (!isLast) Response.Write(",");
Response.Write(" /* fk name column */");
}
}
}
if (null != aliasName)
{
Response.Write(" AS [" + aliasName + "]\r\n");
}
else
{
if (indentLevel >= 0)
{
Response.WriteLine();
}
else if (!isLast)
{
Response.Write(" ");
}
}
}
public bool IsLoopBackKey(ColumnSchema column, ref int keyIndex)
{
bool isLoopBackKey = false;
if (column.IsForeignKeyMember)
{
int fkIndex = -1;
int index = 0;
for(int i=0; i<column.Table.ForeignKeys.Count;i++)
{
TableKeySchema tableKey = column.Table.ForeignKeys[i];
fkIndex = tableKey.ForeignKeyMemberColumns.IndexOf(column);
if (fkIndex != -1)
{
break;
}
index++;
}
if (index > 0)
{
isLoopBackKey = (column.Table.ForeignKeys[index].PrimaryKeyTable == column.Table);
}
}
return isLoopBackKey;
}
public bool IsTitleColumn(ColumnSchema column)
{
return(column.Name.ToLower() == "title");
}
public bool IsTitleColumnCandidate(ColumnSchema column)
{
bool found = false;
if (!found) found = (column.Name.ToLower().IndexOf("title") > 0);
if (!found) found = (column.Name.ToLower().EndsWith("title"));
return found;
}
public ColumnSchema GetTitleColumnCandidate(ColumnSchemaCollection columns)
{
foreach(ColumnSchema column in columns)
{//first look for an exact candidate
if (IsTitleColumn(column))
return column;
}
foreach(ColumnSchema column in columns)
{//now look for any column with title in the name
if (IsTitleColumnCandidate(column))
return column;
}
return null;
}
public bool IsNameColumn(ColumnSchema column)
{
return(column.Name.ToLower() == "name");
}
public bool IsNameColumnCandidate(ColumnSchema column)
{
bool found = false;
if (!found) found = (column.Name.ToLower().IndexOf("name") > 0);
if (!found) found = (column.Name.ToLower().EndsWith("name"));
if (!found) found = (column.Name.ToLower().IndexOf("question") > 0);
if (!found) found = (column.Name.ToLower().EndsWith("question"));
return found;
}
public ColumnSchema GetNameColumnCandidate(ColumnSchemaCollection columns)
{
foreach(ColumnSchema column in columns)
{//first look for an exact candidate
if (IsNameColumn(column))
return column;
}
foreach(ColumnSchema column in columns)
{//now look for any column with name in the name
if (IsNameColumnCandidate(column))
return column;
}
return null;
}
public bool IsNameTitleColumn(ColumnSchema column)
{
return IsNameColumn(column) || IsTitleColumn(column);
}
public bool IsNameTitleColumnCandidate(ColumnSchema column)
{
return IsNameColumnCandidate(column) || IsTitleColumnCandidate(column);
}
public ColumnSchema GetNameTitleColumnCandidate(TableSchema table)
{
ColumnSchema candidateColumn = null;
//hack for user tables.
if (table.Name.ToLower() == "users")
{
foreach(ColumnSchema column in table.Columns)
{
if (column.Name.ToLower() == "userid")
{
candidateColumn = column;
break;
}
}
}
//check if 'table+Name' or 'table+Title'
if (null == candidateColumn)
{
foreach( ColumnSchema column in table.Columns)
{
if (column.Name.ToLower() == StringUtil.ToSingular(table.Name).ToLower() + "title")
{
candidateColumn = column;
break;
}
if (column.Name.ToLower() == StringUtil.ToSingular(table.Name).ToLower() + "name")
{
candidateColumn = column;
break;
}
}
}
//first we check all non primary key columns
if (null == candidateColumn) candidateColumn = GetTitleColumnCandidate(table.NonPrimaryKeyColumns);
if (null == candidateColumn) candidateColumn = GetNameColumnCandidate(table.NonPrimaryKeyColumns);
if (null == candidateColumn)
{
foreach(ColumnSchema column in table.NonPrimaryKeyColumns)
{
if ((column.DataType == DbType.AnsiString ||
column.DataType == DbType.AnsiStringFixedLength ||
column.DataType == DbType.String ||
column.DataType == DbType.StringFixedLength) &&
column.Size <= 150)
{
candidateColumn = column;
break;
}
}
}
//now if none found, we check primary key columns
if (null == candidateColumn) candidateColumn = GetTitleColumnCandidate(table.PrimaryKey.MemberColumns);
if (null == candidateColumn) candidateColumn = GetNameColumnCandidate(table.PrimaryKey.MemberColumns);
if (null == candidateColumn)
{
foreach(ColumnSchema column in table.PrimaryKey.MemberColumns)
{
if ((column.DataType == DbType.AnsiString ||
column.DataType == DbType.AnsiStringFixedLength ||
column.DataType == DbType.String ||
column.DataType == DbType.StringFixedLength) &&
column.Size <= 150)
{
candidateColumn = column;
break;
}
}
}
//if none still foudn, default to first column
if (null == candidateColumn)
{
candidateColumn = table.Columns[0];
}
return candidateColumn;
}
public bool IsMappingTable(TableSchema table)
{
bool isMappingTable = true;
foreach(ColumnSchema column in table.Columns)
{
if (column.IsPrimaryKeyMember)
{
continue;//skip pk columns!
}
else if (!column.IsForeignKeyMember)
{
isMappingTable = false;
break;
}
}
return isMappingTable;
}
public string MakeForeignKeyAlias(string columnName, string candidateColumnName)
{
//remove id from column.
columnName = StringUtil.ToPascalCase(columnName);
if (columnName.EndsWith("ID"))
columnName = columnName.Replace("ID", "_Name");
else
columnName = columnName + "_Name";
return columnName;
//remove duplicate words.
//eg. CreditCardIssuerIssuerName
//columnName = columnName;
//return concatenation of both columns as alias.
//return StringUtil.ToPascalCase(columnName + "_" + candidateColumnName.Substring(0,1).ToUpper() + candidateColumnName.Substring(1));
}
public void GenerateCommentedKeyMarkers(ColumnSchema column)
{
if (column.IsPrimaryKeyMember)
{
Response.Write(" /* pk */");
}
else if (column.IsForeignKeyMember)
{
Response.Write(" /* fk */");
}
else if (column.IsUnique)
{
Response.Write(" /* unique */");
}
}
public void GenerateTableName(bool includeTableOwner, int indentLevel)
{
GenerateTableName(this.SourceTable, includeTableOwner, indentLevel);
}
public void GenerateTableName(TableSchema table, bool includeTableOwner, int indentLevel)
{
WriteIndentedLine(GetTableOwner(table) + "[" + table.Name + "]", indentLevel);
}
public void GenerateColumns(ColumnSchemaCollection columns, int indentLevel)
{
GenerateColumns(columns, indentLevel, false);
}
public void GenerateColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner)
{
GenerateColumns(columns, indentLevel, includeTableOwner, true);
}
public void GenerateColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, bool showKeyMarkers)
{
GenerateColumns(columns, indentLevel, includeTableOwner, showKeyMarkers, true);
}
public void GenerateColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, bool showKeyMarkers, bool includeForeignKeyNameCandidate)
{
GenerateColumns(columns, indentLevel, includeTableOwner, showKeyMarkers, includeForeignKeyNameCandidate, false);
}
public void GenerateColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, bool showKeyMarkers, bool includeForeignKeyNameCandidate, bool includeTrailingComma)
{
ColumnSchemaCollection filteredColumns = columns; //FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateColumn(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1 && !includeTrailingComma, includeTableOwner, showKeyMarkers, includeForeignKeyNameCandidate);
}
}
public void GeneratePagedColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner)
{
GeneratePagedColumns(columns, indentLevel, includeTableOwner, true, false, false);
}
public void GeneratePagedColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, bool showKeyMarkers)
{
GeneratePagedColumns(columns, indentLevel, includeTableOwner, showKeyMarkers, false, false);
}
public void GeneratePagedColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, bool showKeyMarkers, bool includeTrailingComma)
{
GeneratePagedColumns(columns, indentLevel, includeTableOwner, showKeyMarkers, includeTrailingComma, false);
}
public void GeneratePagedColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, bool showKeyMarkers, bool includeTrailingComma, bool fkAliasOnly)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
//determine if last column is commented
bool lastIsCommented = false;
//determine the index of the last uncommented column
int indexOfLastUnCommented = 0;
for (int x=filteredColumns.Count-1; x >= 0; x--)
{
bool isCommented = FilterPagedColumn(filteredColumns[x]);
lastIsCommented = (x==filteredColumns.Count-1 && isCommented);
if (!isCommented)
{
indexOfLastUnCommented = x;
break;
}
}
//now generate the columns
for (int i=0; i < filteredColumns.Count; i++)
{
bool isCommented = FilterPagedColumn(filteredColumns[i]);
bool doCommaSeparate = ((!lastIsCommented && (i == indexOfLastUnCommented)) || (i == filteredColumns.Count-1));
//include trailing comma.
if (i==filteredColumns.Count-1 && includeTrailingComma)
{
doCommaSeparate = false;
}
this.GenerateColumn(filteredColumns[i], indentLevel, i==0, doCommaSeparate, includeTableOwner, showKeyMarkers, this.IncludeForeignKeyNameCandidate, isCommented, fkAliasOnly);
}
}
public bool FilterPagedColumn(ColumnSchema column)
{
if (ColumnIsTextual(column) && this.MaxStringLength > 0 && column.Size > this.MaxStringLength)
return true;
else if (ColumnIsTextual(column) && column.NativeType == "text")
return true;
else if (column.DataType == DbType.Binary ||
column.DataType == DbType.Byte ||
column.DataType == DbType.Object ||
column.DataType == DbType.SByte )
return true;
return false;
}
public void GenerateConcatenatedColumns(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner)
{
for(int x=0; x < columns.Count; x++)
{
bool isLast = (x==columns.Count-1);
ColumnSchema column = columns[x];
if (x == 0)
GenerateIndent(indentLevel);
if (!ColumnIsTextual(column) && columns.Count > 1)
Response.Write("CAST(");
if (includeTableOwner)
{
Response.Write(GetTableOwner() + "[" + column.Table.Name + "].");
}
Response.Write("[");
string columnName = column.Name;
Response.Write(columnName);
Response.Write("]");
if (!ColumnIsTextual(column) && columns.Count > 1)
Response.Write(" AS VARCHAR)");
if (!isLast) Response.Write(" + ',' + ");
}
}
public bool IsBitOn(int val, int bitToCheck)
{
return (val >> bitToCheck & 0x01) == 0x01;
}
public void GenerateUpdateConditionalStatements(ColumnSchemaCollection conditionalColumns, int index, int indentLevel, ref int val, string procedureName)
{
TableSchema sourceTable = conditionalColumns[0].Table;
if (index != conditionalColumns.Count)
{//non-leaf node
indentLevel++;;
GenerateIndent(indentLevel);
Response.Write("IF(@" + conditionalColumns[index].Name + " IS NULL)");
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write("BEGIN");
Response.WriteLine();
Response.WriteLine();
//recursion - binary tree
GenerateUpdateConditionalStatements(conditionalColumns, index+1, indentLevel, ref val, procedureName);
GenerateIndent(indentLevel);
Response.Write("END");
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write("ELSE");
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write("BEGIN");
Response.WriteLine();
Response.WriteLine();
//recursion - binary tree
GenerateUpdateConditionalStatements(conditionalColumns, index+1, indentLevel, ref val, procedureName);
GenerateIndent(indentLevel);
Response.Write("END");
Response.WriteLine();
}
else
{//leaf node
indentLevel++;
//display bit combination string
GenerateIndent(indentLevel);
Response.Write("--" + Convert.ToString(val,2).PadLeft(conditionalColumns.Count,'0'));
Response.WriteLine();
//get columns to use in update statement
ColumnSchemaCollection onColumns = GetConditionalTrueColumns(conditionalColumns, val);
if (onColumns.Count > 0)
{
GenerateIndent(indentLevel);
Response.Write("UPDATE");
Response.WriteLine();
GenerateIndent(indentLevel+1);
Response.Write(sourceTable.Name);
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write("SET");
Response.WriteLine();
//display updates
for(int i=0; i < onColumns.Count; i++)
{
GenerateUpdate(onColumns[i], indentLevel+1, i==0, i==onColumns.Count-1 );
}
GenerateIndent(indentLevel);
Response.Write("WHERE");
Response.WriteLine();
GenerateConditions(sourceTable.PrimaryKey.MemberColumns, indentLevel+1, false);
//Response.WriteLine();
//Response.WriteLine();
//GenerateIndent(indentLevel);
//Response.Write("/* must use single statement immediately to store system functions ");
//Response.WriteLine();
//GenerateIndent(indentLevel);
//Response.Write("as all DML statements, SELECT, IF, PRINT and SET will reset @@error to zero */");
//Response.WriteLine();
//GenerateIndent(indentLevel);
//Response.Write("SELECT");
//Response.WriteLine();
//GenerateIndent(indentLevel+1);
//Response.Write("@ErrStatus = @@ERROR,");
//Response.WriteLine();
//GenerateIndent(indentLevel+1);
//Response.Write("@RowsAffected = @@ROWCOUNT");
//Response.WriteLine();
}
else
{//if no optional parameters found, display rollback and display error
GenerateIndent(indentLevel);
Response.Write("IF @@TRANCOUNT <> 0");
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write(" ROLLBACK TRANSACTION");
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write("RAISERROR('Must provide at least one optional parameter for ''" + procedureName + "''', 15, 1)");
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write("RETURN -201 -- expecting parameter code!");
Response.WriteLine();
}
Response.WriteLine();
//now increment running count
val++;
}
}
public ColumnSchemaCollection GetConditionalTrueColumns(ColumnSchemaCollection columns, int val)
{
ColumnSchemaCollection onColumns = new ColumnSchemaCollection();
for(int i=0; i < columns.Count; i++)
{
//must reverse as shift from right to left (not left to right)
int reverseIndex = Math.Abs(i-(columns.Count-1));
if (IsBitOn(val, reverseIndex))
{
onColumns.Add(columns[i]);
}
}
return onColumns;
}
//-------------------------------------------------------------------------------------
public void GenerateIfStatement(ColumnSchema column, int indentLevel, string statementOperator, string rhsStatement, bool doCloseBraces)
{
GenerateIndent(indentLevel);
Response.Write("IF(@" + column.Name + " " + statementOperator + " " + rhsStatement + ")");
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write("BEGIN");
Response.WriteLine();
}
public void GenerateElseStatement(int indentLevel)
{
GenerateIndent(indentLevel);
Response.Write("ELSE");
Response.WriteLine();
GenerateIndent(indentLevel);
Response.Write("BEGIN");
Response.WriteLine();
}
public void GenerateEndStatement(int indentLevel)
{
GenerateIndent(indentLevel);
Response.Write("END");
Response.WriteLine();
}
public void GenerateUpdate(ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateIndent(indentLevel);
Response.Write("[");
Response.Write(column.Name);
Response.Write("] = @");
Response.Write(column.Name);
if (!isLast) Response.Write(",");
//display key markers
//if (showKeyMarkers)
GenerateCommentedKeyMarkers(column);
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateUpdates(ColumnSchemaCollection columns, int indentLevel)
{
ColumnSchemaCollection filteredColumns = FilterReadOnlyAndExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateUpdate(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1);
}
}
public void GenerateUpdateWithPrefix(string prefix, ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateIndent(indentLevel);
Response.Write("[");
Response.Write(column.Name);
Response.Write("] = @" + prefix);
Response.Write(column.Name);
if (!isLast) Response.Write(",");
//display key markers
//if (showKeyMarkers)
GenerateCommentedKeyMarkers(column);
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateUpdatesWithPrefix(string prefix, ColumnSchemaCollection columns, int indentLevel)
{
ColumnSchemaCollection filteredColumns = FilterReadOnlyAndExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateUpdateWithPrefix(prefix, filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1);
}
}
public void GenerateRowCountStatement(string rowCountValue, int indentLevel)
{
GenerateIndent(indentLevel);
Response.Write("SET ROWCOUNT " + rowCountValue + "\n");
}
public string GetConditionDynamicSql(ColumnSchema column, bool isFirst, bool isLast)
{
return GetConditionDynamicSql(column, isFirst, isLast, false, "AND");
}
public string GetConditionDynamicSql(ColumnSchema column, bool isFirst, bool isLast, bool includeTableOwner)
{
return GetConditionDynamicSql(column, isFirst, isLast, includeTableOwner, "AND");
}
public string GetConditionDynamicSql(ColumnSchema column, bool isFirst, bool isLast, bool includeTableOwner, string logicSeparator)
{
string s = String.Empty;
if (!isFirst)
{//include logic separator - "AND" or "OR"
s += logicSeparator + " ";
}
if (includeTableOwner)
{//display full path for all columns - saves creating an aliasing algorithm and doesnt read poorly!
s += GetTableOwner() + "[" + column.Table.Name + "].";
}
s += "[";
s += column.Name;
if (this.ColumnIsTextual(column))
{
s += "] = ''' + @";
s += column.Name;
s += " + ''''";
}
else
{
s += "] = ' + CAST(@";
s += column.Name + " AS varchar)";
}
//display key markers
//if (showKeyMarkers)
// GenerateCommentedKeyMarkers(column);
if (!isLast)
{
s += " ";
}
return s;
}
public void GenerateCondition(ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateCondition(column, indentLevel, isFirst, isLast, false, "AND");
}
public void GenerateCondition(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner)
{
GenerateCondition(column, indentLevel, isFirst, isLast, includeTableOwner, "AND");
}
public void GenerateCondition(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, string logicSeparator)
{
GenerateIndent(indentLevel);
if (!isFirst)
{//include logic separator - "AND" or "OR"
Response.Write(logicSeparator + " ");
}
if (includeTableOwner)
{//display full path for all columns - saves creating an aliasing algorithm and doesnt read poorly!
Response.Write(GetTableOwner() + "[" + column.Table.Name + "].");
}
Response.Write("[");
Response.Write(column.Name);
Response.Write("] = @");
Response.Write(column.Name);
//display key markers
//if (showKeyMarkers)
// GenerateCommentedKeyMarkers(column);
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateConditions(ColumnSchemaCollection columns, int indentLevel)
{
GenerateConditions(columns, indentLevel, false, "AND");
}
public void GenerateConditions(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner)
{
GenerateConditions(columns, indentLevel, includeTableOwner, "AND");
}
public void GenerateConditions(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, string logicSeparator)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateCondition(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1, includeTableOwner, logicSeparator);
}
}
public void GenerateOptionalCondition(ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateOptionalCondition(column, indentLevel, isFirst, isLast, false, "AND");
}
public void GenerateOptionalCondition(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner)
{
GenerateOptionalCondition(column, indentLevel, isFirst, isLast, includeTableOwner, "AND");
}
public void GenerateOptionalCondition(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, string logicSeparator)
{
GenerateIndent(indentLevel);
if (!isFirst)
{//include logic separator - "AND" or "OR"
Response.Write(logicSeparator + " ");
}
//if (!(isFirst && isLast))
//{
Response.Write("(");
//}
Response.Write("@" + column.Name + " IS NULL OR ");
if (includeTableOwner)
{
Response.Write(GetTableOwner() + "[" + column.Table.Name + "].");
}
Response.Write("[" + column.Name + "] = @" + column.Name + "");
//if (!(isFirst && isLast))
Response.Write(")");
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateOptionalConditions(ColumnSchemaCollection columns, int indentLevel)
{
GenerateOptionalConditions(columns, indentLevel, false, "AND");
}
public void GenerateOptionalConditions(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner)
{
GenerateOptionalConditions(columns, indentLevel, includeTableOwner, "AND");
}
public void GenerateOptionalConditions(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, string logicSeparator)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateOptionalCondition(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1, includeTableOwner, logicSeparator);
}
}
public void GenerateOptionalParametersNullCheck(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, string logicSeparator)
{
GenerateIndent(indentLevel);
if (!isFirst)
{//include logic separator - "AND" or "OR"
Response.Write(logicSeparator + " ");
}
if (!(isFirst && isLast))
{
Response.Write("(");
}
Response.Write("@" + column.Name + " IS NULL");
if (!(isFirst && isLast))
Response.Write(")");
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateOptionalConditionNullChecks(ColumnSchemaCollection columns, int indentLevel, string logicSeparator)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateOptionalParametersNullCheck(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1, logicSeparator);
}
}
public void GenerateLikeConditions(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, string logicSeparator, string searchText)
{
int newIndentLevel = 0;
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
if (i> 0) newIndentLevel = indentLevel;
GenerateLikeCondition(filteredColumns[i], newIndentLevel, i == 0, i == filteredColumns.Count - 1, includeTableOwner, logicSeparator, searchText);
}
}
//TODO: Make an enumeration for "logicSeparator" - ELogicalJoin.And,Or,Xor
public void GenerateLikeCondition(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, string logicSeparator, string searchText)
{
GenerateIndent(indentLevel);
if (includeTableOwner)
{
Response.Write(GetTableOwner() + "[" + column.Table.Name + "].");
}
Response.Write("[");
Response.Write(column.Name);
Response.Write("] LIKE '%' + " + searchText + " + '%'");
if (!isLast)
{
Response.Write(" " + logicSeparator + " ");
}
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateDynamicSqlLikeConditions(ColumnSchemaCollection columns, int indentLevel, bool includeTableOwner, string logicSeparator, string searchText)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateDynamicSqlLikeConditions(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1, includeTableOwner, logicSeparator, searchText);
}
}
//TODO: Make an enumeration for "logicSeparator" - ELogicalJoin.And,Or,Xor
public void GenerateDynamicSqlLikeConditions(ColumnSchema column, int indentLevel, bool isFirst, bool isLast, bool includeTableOwner, string logicSeparator, string searchText)
{
GenerateIndent(indentLevel);
if (includeTableOwner)
{
Response.Write(GetTableOwner() + "[" + column.Table.Name + "].");
}
Response.Write("[");
Response.Write(column.Name);
Response.Write("] LIKE ''%''' + " + searchText + " + '''%''");
if (!isLast)
{
Response.Write(" " + logicSeparator + " ");
}
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateVariable(ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateIndent(indentLevel);
Response.Write("@");
Response.Write(column.Name);
if (!isLast) Response.Write(",");
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateVariables(ColumnSchemaCollection columns, int indentLevel)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateVariable(filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1);
}
}
public void GenerateVariableWithPrefix(string prefix, ColumnSchema column, int indentLevel, bool isFirst, bool isLast)
{
GenerateIndent(indentLevel);
Response.Write("@" + prefix);
Response.Write(column.Name);
if (!isLast) Response.Write(",");
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (!isLast)
{
Response.Write(" ");
}
}
public void GenerateVariablesWithPrefix(string prefix, ColumnSchemaCollection columns, int indentLevel)
{
ColumnSchemaCollection filteredColumns = FilterExcludedColumns(columns);
for (int i = 0; i < filteredColumns.Count; i++)
{
GenerateVariableWithPrefix(prefix, filteredColumns[i], indentLevel, i == 0, i == filteredColumns.Count - 1);
}
}
public void GenerateJoinStatements(TableSchema table, int indentLevel)
{
GenerateJoinStatements(table, indentLevel, false);
}
public void GenerateJoinStatements(TableSchema table, int indentLevel, bool useInnerJoinOnly)
{
if (this.IncludeJoinStatements)
{
//stores all pk table names
string[] pkTableNames = new string[table.ForeignKeys.Count];
//create join statements
int tableKeyCount = 0;
foreach(TableKeySchema tableKeys in table.ForeignKeys)
{
bool isLeftJoin = tableKeys.ForeignKeyMemberColumns[0].AllowDBNull;
if ((useInnerJoinOnly && !isLeftJoin) || !useInnerJoinOnly)
{
//get pk table name
string pkTableName = tableKeys.PrimaryKeyTable.Name;
//loopback join (e.g. ParentCategoryID)
bool isLoopBackJoin = (pkTableName == table.Name);
//generate
GenerateIndent(indentLevel);
//check if table has already been joined each time.
int joinCount = 0;
for (int jj=0; jj < tableKeyCount; jj++)
{
if (pkTableNames[jj] == pkTableName)
{
joinCount++;
}
}
//add joined table to array.
pkTableNames[tableKeyCount] = pkTableName;
string aliasName = String.Empty;
if (joinCount > 0 || isLoopBackJoin)
{
aliasName = pkTableName + "_" + (joinCount+1).ToString().PadLeft(2, '0');
}
//TODO: FIX TO HANDLE COMPOSITE KEY!!
if (isLeftJoin)
{//if any foreign key is nullable, left outer join
if (joinCount > 0 || isLoopBackJoin)
Response.Write("LEFT OUTER JOIN " + GetTableOwner() + "[" + pkTableName + "] AS [" + aliasName + "] ON ");
else
Response.Write("LEFT OUTER JOIN " + GetTableOwner() + "[" + pkTableName + "] ON ");
}
else
{//referential integrity
if (joinCount > 0 || isLoopBackJoin)
Response.Write("INNER JOIN " + GetTableOwner() + "[" + pkTableName + "] AS [" + aliasName + "] ON ");
else
Response.Write("INNER JOIN " + GetTableOwner() + "[" + pkTableName + "] ON ");
}
//lhs
for(int i=0; i < tableKeys.ForeignKeyMemberColumns.Count; i++)
{
Response.Write(GetTableOwner() + "[" + this.SourceTable.Name + "].[" + tableKeys.ForeignKeyMemberColumns[i].Name + "]");
if (i < tableKeys.ForeignKeyMemberColumns.Count-1)
Response.Write(" AND ");
}
//operator
Response.Write(" = ");
//rhs
for(int i=0; i < tableKeys.ForeignKeyMemberColumns.Count; i++)
{
if (joinCount > 0 || isLoopBackJoin)
Response.Write("[" + aliasName + "].[" + tableKeys.PrimaryKeyTable.PrimaryKey.MemberColumns[i].Name + "]");
else
Response.Write(GetTableOwner() + "[" + tableKeys.PrimaryKeyTable.Name + "].[" + tableKeys.PrimaryKeyTable.PrimaryKey.MemberColumns[i].Name + "]");
if (i < tableKeys.ForeignKeyMemberColumns.Count-1)
Response.Write(" AND ");
}
Response.WriteLine();
//increment key count
tableKeyCount++;
}
}
}
}
public void GenerateDeleteReferenceKeyJoinStatements(TableSchema table, TableSchema refTable, int indentLevel)
{
GenerateDeleteReferenceKeyJoinStatements(table, refTable, indentLevel, false);
}
public void GenerateDeleteReferenceKeyJoinStatements(TableSchema table, TableSchema refTable, int indentLevel, bool useInnerJoinOnly)
{
//if (this.IncludeJoinStatements)
//{
//stores all pk table names
string[] pkTableNames = new string[table.ForeignKeys.Count];
//create join statements
int tableKeyCount = 0;
foreach(TableKeySchema tableKeys in table.ForeignKeys)
{
bool isLeftJoin = tableKeys.ForeignKeyMemberColumns[0].AllowDBNull;
if (((useInnerJoinOnly && !isLeftJoin) || !useInnerJoinOnly) && (tableKeys.PrimaryKeyTable == refTable))
{
//get pk table name
string pkTableName = tableKeys.PrimaryKeyTable.Name;
//loopback join (e.g. ParentCategoryID)
bool isLoopBackJoin = (pkTableName == table.Name);
//generate
GenerateIndent(indentLevel);
//check if table has already been joined each time.
int joinCount = 0;
for (int jj=0; jj < tableKeyCount; jj++)
{
if (pkTableNames[jj] == pkTableName)
{
joinCount++;
}
}
//add joined table to array.
pkTableNames[tableKeyCount] = pkTableName;
string aliasName = String.Empty;
if (joinCount > 0 || isLoopBackJoin)
{
aliasName = pkTableName + "_" + (joinCount+1).ToString().PadLeft(2, '0');
}
//TODO: FIX TO HANDLE COMPOSITE KEY!!
if (isLeftJoin)
{//if any foreign key is nullable, left outer join
if (joinCount > 0 || isLoopBackJoin)
Response.Write("LEFT OUTER JOIN " + GetTableOwner() + "[" + pkTableName + "] AS [" + aliasName + "] ON ");
else
Response.Write("LEFT OUTER JOIN " + GetTableOwner() + "[" + pkTableName + "] ON ");
}
else
{//referential integrity
if (joinCount > 0 || isLoopBackJoin)
Response.Write("INNER JOIN " + GetTableOwner() + "[" + pkTableName + "] AS [" + aliasName + "] ON ");
else
Response.Write("INNER JOIN " + GetTableOwner() + "[" + pkTableName + "] ON ");
}
//lhs
for(int i=0; i < tableKeys.ForeignKeyMemberColumns.Count; i++)
{
Response.Write(GetTableOwner() + "[" + this.SourceTable.Name + "].[" + tableKeys.ForeignKeyMemberColumns[i].Name + "]");
if (i < tableKeys.ForeignKeyMemberColumns.Count-1)
Response.Write(" AND ");
}
//operator
Response.Write(" = ");
//rhs
for(int i=0; i < tableKeys.ForeignKeyMemberColumns.Count; i++)
{
if (joinCount > 0 || isLoopBackJoin)
Response.Write("[" + aliasName + "].[" + tableKeys.PrimaryKeyTable.PrimaryKey.MemberColumns[i].Name + "]");
else
Response.Write(GetTableOwner() + "[" + tableKeys.PrimaryKeyTable.Name + "].[" + tableKeys.PrimaryKeyTable.PrimaryKey.MemberColumns[i].Name + "]");
if (i < tableKeys.ForeignKeyMemberColumns.Count-1)
Response.Write(" AND ");
}
Response.WriteLine();
//increment key count
tableKeyCount++;
}
}
//}
}
public void GetDefaultOrderByColumn(ref string columnName, ref string sortDirection)
{
bool found = false;
//use [OrderIndex] column for sorting if available
foreach(ColumnSchema c in this.SourceTable.Columns)
{
if ((c.DataType == DbType.Int16 || c.DataType == DbType.Int32 || c.DataType == DbType.Int64) && c.Name.ToUpper() == "ORDERINDEX")
{
columnName = c.Name;
sortDirection = "ASC";
found = true;
break;
}
}
//use [PublishDate] column for sorting if available
if (!found)
{
foreach(ColumnSchema c in this.SourceTable.Columns)
{
if ((c.DataType == DbType.Date ||
c.DataType == DbType.DateTime ||
c.DataType == DbType.Time) &&
c.Name.ToUpper() == "PUBLISHDATE")
{
columnName = c.Name;
sortDirection = "DESC";
found = true;
break;
}
}
}
//use [CreatedDate] column for sorting if available
if (!found)
{
foreach(ColumnSchema c in this.SourceTable.Columns)
{
if ((c.DataType == DbType.Date ||
c.DataType == DbType.DateTime ||
c.DataType == DbType.Time) &&
c.Name.ToUpper() == "CREATEDDATE")
{
columnName = c.Name;
sortDirection = "DESC";
found = true;
break;
}
}
}
//use NameTitle column for sorting if available
if (!found)
{
ColumnSchema c = this.GetNameTitleColumnCandidate(this.SourceTable);
if (null != c)
{
columnName = c.Name;
sortDirection = "ASC";
found = true;
}
}
//if no created date, order by auto-primary key
if (!found)
{
if (this.SourceTable.PrimaryKey.MemberColumns.Count == 1
&& (this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Guid
|| ((this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int16
|| this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int32
|| this.SourceTable.PrimaryKey.MemberColumns[0].DataType == DbType.Int64)
&& (bool)this.SourceTable.PrimaryKey.MemberColumns[0].ExtendedProperties["CS_IsIdentity"].Value == true)))
{
ColumnSchema pkColumn = this.SourceTable.PrimaryKey.MemberColumns[0];
columnName = pkColumn.Name;
sortDirection = "ASC";
found = true;
}
}
//if no created date, nor an auto-primary key, order primary key columns
if (!found)
{
for(int i=0; i < this.SourceTable.PrimaryKey.MemberColumns.Count; i++)
{
if (i > 0)
columnName += ", ";
columnName = this.SourceTable.PrimaryKey.MemberColumns[i].Name;
sortDirection = "ASC";
found = true;
break;
}
}
/* DEPRECATED!! */
/*
if (!found)
{
columnName = "1";
sortDirection = "ASC";
}*/
}
public void GenerateSortParameters(int indentLevel)
{
GenerateSortParameters(indentLevel, false);
}
public void GenerateSortParameters(int indentLevel, bool includeTrailingComma)
{
string sortColumn = "NULL";
string sortDirection = "ASC";
this.GetDefaultOrderByColumn(ref sortColumn, ref sortDirection);
WriteIndentedLine("@SortBy varchar(50) = '" + sortColumn + "', ", indentLevel);
WriteIndentedLine("@SortDirection varchar(4) = '" + sortDirection + "'" + ((includeTrailingComma)? ", ": ""), indentLevel);
}
public void GenerateItemCountParameters(int indentLevel)
{
GenerateItemCountParameters(indentLevel, false);
}
public void GenerateItemCountParameters(int indentLevel, bool includeTrailingComma)
{
WriteIndentedLine("@IncludeItemCount bit = 0, ", indentLevel);
WriteIndentedLine("@ItemCount bigint = 0 OUTPUT" + ((includeTrailingComma)? ", ": ""), indentLevel);
}
public void GenerateVirtualItemCountParameters(int indentLevel)
{
GenerateVirtualItemCountParameters(indentLevel, false);
}
public void GenerateVirtualItemCountParameters(int indentLevel, bool includeTrailingComma)
{
GenerateItemCountParameters(indentLevel, true);
WriteIndentedLine("@VirtualItemCount bigint = 0 OUTPUT" + ((includeTrailingComma)? ", ": ""), indentLevel);
}
public void GenerateOrderByClause(ColumnSchemaCollection sortableColumns, int indentLevel, bool includeTableOwner)
{
string defaultSortColumnName = String.Empty;
string defaultSortDirection = "ASC";
this.GetDefaultOrderByColumn(ref defaultSortColumnName, ref defaultSortDirection);
string tableOwner = string.Empty;
if (includeTableOwner)
{
tableOwner = GetTableOwner();
}
//create order by statement
WriteIndentedLine("ORDER BY", indentLevel);
if (null == sortableColumns || sortableColumns.Count == 0)
{
WriteIndentedLine("\t" + tableOwner + "[" + this.SourceTable.Name + "].[" + defaultSortColumnName + "] " + defaultSortDirection, indentLevel);
}
else
{
string trailingComma = ", ";
//asc
WriteIndentedLine("-- asc", indentLevel+1);
for(int i=0; i<sortableColumns.Count; i++)
{
WriteIndentedLine("CASE WHEN LOWER(@SortBy) = '" + sortableColumns[i].Name.ToLower() + "' AND UPPER(@SortDirection) = 'ASC' THEN", indentLevel+1);
WriteIndentedLine("\t" + tableOwner + "[" + this.SourceTable.Name + "].[" + sortableColumns[i].Name + "] END ASC" + trailingComma, indentLevel+1);
GenerateOrderByFkAliasName(sortableColumns[i], indentLevel, includeTableOwner, false, "ASC");
}
Response.WriteLine();
//desc
WriteIndentedLine("-- desc", indentLevel+1);
for(int i=0; i<sortableColumns.Count; i++)
{
if ((i==sortableColumns.Count-1) && !sortableColumns[i].IsForeignKeyMember)
trailingComma = string.Empty;
WriteIndentedLine("CASE WHEN LOWER(@SortBy) = '" + sortableColumns[i].Name.ToLower() + "' AND UPPER(@SortDirection) = 'DESC' THEN", indentLevel+1);
WriteIndentedLine("\t" + tableOwner + "[" + this.SourceTable.Name + "].[" + sortableColumns[i].Name + "] END DESC" + trailingComma, indentLevel+1);
GenerateOrderByFkAliasName(sortableColumns[i], indentLevel, includeTableOwner, i==sortableColumns.Count-1, "DESC");
}
}
}
public void GenerateOrderByClause(ColumnSchemaCollection sortableColumns, int indentLevel)
{
GenerateOrderByClause(sortableColumns, indentLevel, true);
}
public void GenerateOrderByFkAliasName(ColumnSchema column, int indentLevel, bool includeTableOwner, bool isLast, string sortDirection)
{
if (column.IsForeignKeyMember)
{
string tableOwner = string.Empty;
if (includeTableOwner)
{
tableOwner = GetTableOwner();
}
//find key index
int keyIndex = 0;
for(int i=0; i < column.Table.ForeignKeys.Count; i++)
{
//TODO: FIX TO HANDLE COMPOSITE KEY!!
if (column.Name == column.Table.ForeignKeys[i].ForeignKeyMemberColumns[0].Name)
{
keyIndex = i;
break;
}
}
string trailingComma = isLast? "": ",";
//now display key as an aliased column
TableSchema foreignTable = column.Table.ForeignKeys[keyIndex].PrimaryKeyTable;
ColumnSchema candidateColumn = GetNameTitleColumnCandidate(foreignTable);
if (null != candidateColumn)
{
string fkAlias = MakeForeignKeyAlias(column.Name, candidateColumn.Name);
WriteIndentedLine("CASE WHEN LOWER(@SortBy) = '" + fkAlias.ToLower() + "' AND UPPER(@SortDirection) = '" + sortDirection + "' THEN", indentLevel+1);
WriteIndentedLine("\t" + tableOwner + "[" + foreignTable.Name + "].[" + candidateColumn.Name + "] END " + sortDirection + "" + trailingComma, indentLevel+1);
}
}
}
public void GenerateListOrderByClause(int indentLevel)
{
GenerateListOrderByClause(indentLevel, true);
}
public void GenerateListOrderByClause(int indentLevel, bool includeTableOwner)
{
WriteIndentedLine("ORDER BY", indentLevel);
bool hasOrderIndex = false;
foreach(ColumnSchema column in this.SourceTable.Columns)
{
if (column.Name.ToLower() == "orderindex")
{
hasOrderIndex = true;
if (includeTableOwner)
{
WriteIndentedLine("\t" + GetTableOwner() + "[" + this.SourceTable.Name + "].[" + column.Name + "] ASC", indentLevel);
}
else
{
WriteIndentedLine("\t" + "[" + this.SourceTable.Name + "].[" + column.Name + "] ASC", indentLevel);
}
break;
}
}
if (!hasOrderIndex)
{
WriteIndentedLine("\t2 ASC -- order by name", indentLevel);
}
}
public ColumnSchemaCollection FilterSearchableColumns(ColumnSchemaCollection columns)
{
ColumnSchemaCollection filteredColumns = new ColumnSchemaCollection();
//filter excluded columns
filteredColumns = this.FilterExcludedColumns(columns);
//get all string based columns.
filteredColumns = this.FilterNonTextualColumns(filteredColumns);
//include guids.
for (int i = 0; i < columns.Count; i++)
{
if (columns[i].DataType == DbType.Guid) filteredColumns.Add(columns[i]);
}
//if none found still, must include int fields
if (filteredColumns == null || filteredColumns.Count == 0)
{
for (int i = 0; i < columns.Count; i++)
{
if (ColumnIsIntBased(columns[i])) filteredColumns.Add(columns[i]);
}
}
return filteredColumns;
}
public ColumnSchemaCollection FilterNonTextualColumns(ColumnSchemaCollection columns)
{
ColumnSchemaCollection filteredColumns = new ColumnSchemaCollection();
for (int i = 0; i < columns.Count; i++)
{
if (ColumnIsTextual(columns[i])) filteredColumns.Add(columns[i]);
}
return filteredColumns;
}
public bool ColumnIsTextual(ColumnSchema column)
{
return (
column.DataType == DbType.AnsiString ||
column.DataType == DbType.AnsiStringFixedLength ||
column.DataType == DbType.String ||
column.DataType == DbType.StringFixedLength
);
}
public bool ColumnIsIntBased(ColumnSchema column)
{
return (
column.DataType == DbType.Int16 ||
column.DataType == DbType.Int32 ||
column.DataType == DbType.Int64 ||
column.DataType == DbType.UInt16 ||
column.DataType == DbType.UInt32 ||
column.DataType == DbType.UInt64 ||
column.DataType == DbType.Single
);
}
//----------------------------
public ColumnSchemaCollection FilterReadOnlyColumns(ColumnSchemaCollection columns)
{
ColumnSchemaCollection filteredColumns = new ColumnSchemaCollection();
for (int i = 0; i < columns.Count; i++)
{
if (!ColumnIsReadOnly(columns[i])) filteredColumns.Add(columns[i]);
}
return filteredColumns;
}
public ColumnSchemaCollection FilterExcludedColumns(ColumnSchemaCollection columns)
{
ColumnSchemaCollection filteredColumns = new ColumnSchemaCollection();
for (int i = 0; i < columns.Count; i++)
{
if (!ColumnIsExcluded(columns[i])) filteredColumns.Add(columns[i]);
}
return filteredColumns;
}
public ColumnSchemaCollection FilterReadOnlyAndExcludedColumns(ColumnSchemaCollection columns)
{
ColumnSchemaCollection filteredColumns = new ColumnSchemaCollection();
for (int i = 0; i < columns.Count; i++)
{
if (!ColumnIsExcludedOrReadOnly(columns[i])) filteredColumns.Add(columns[i]);
}
return filteredColumns;
}
public ColumnSchemaCollection FilterExcludedInsertColumns(ColumnSchemaCollection columns)
{
ColumnSchemaCollection filteredColumns = new ColumnSchemaCollection();
for (int i = 0; i < columns.Count; i++)
{
if (!IsExcludedInsertColumn(columns[i])) filteredColumns.Add(columns[i]);
}
return filteredColumns;
}
public ColumnSchemaCollection FilterExcludedUpdateColumns(ColumnSchemaCollection columns)
{
ColumnSchemaCollection filteredColumns = new ColumnSchemaCollection();
for (int i = 0; i < columns.Count; i++)
{
if (!IsExcludedUpdateColumn(columns[i])) filteredColumns.Add(columns[i]);
}
return filteredColumns;
}
private Regex excludedColumnRegex = null;
public bool ColumnIsExcluded(ColumnSchema column)
{
if (column.IsPrimaryKeyMember) return false;
if (excludedColumnRegex == null)
{
if (ExcludedColumns != null && ExcludedColumns.Count > 0)
{
string excluded = String.Empty;
for (int i = 0; i < ExcludedColumns.Count; i++)
{
if (ExcludedColumns[i].Trim().Length > 0)
{
excluded += "(" + Regex.Escape(ExcludedColumns[i]).Replace("\\*", ".*?") + ")|";
}
}
if (excluded.Length > 0)
{
excluded = excluded.Substring(0, excluded.Length - 1);
excludedColumnRegex = new Regex(excluded, RegexOptions.IgnoreCase);
}
}
}
if (excludedColumnRegex != null && excludedColumnRegex.IsMatch(column.Name)) return true;
return false;
}
private Regex readOnlyColumnRegex = null;
public bool ColumnIsReadOnly(ColumnSchema column)
{
if (column.IsPrimaryKeyMember) return false;
if (readOnlyColumnRegex == null)
{
if (ReadOnlyColumns != null && ReadOnlyColumns.Count > 0)
{
string readOnly = String.Empty;
for (int i = 0; i < ReadOnlyColumns.Count; i++)
{
if (ReadOnlyColumns[i].Trim().Length > 0)
{
readOnly += "(" + Regex.Escape(ReadOnlyColumns[i]).Replace("\\*", ".*?") + ")|";
}
}
if (readOnly.Length > 0)
{
readOnly = readOnly.Substring(0, readOnly.Length - 1);
readOnlyColumnRegex = new Regex(readOnly, RegexOptions.IgnoreCase);
}
}
}
if (readOnlyColumnRegex != null && readOnlyColumnRegex.IsMatch(column.Name)) return true;
return false;
}
private Regex excludedInsertColumnRegex = null;
public bool ColumnIsExcludedInsert(ColumnSchema column)
{
if (column.IsPrimaryKeyMember) return false;
if (excludedInsertColumnRegex == null)
{
if (ExcludedInsertColumns != null && ExcludedInsertColumns.Count > 0)
{
string excluded = String.Empty;
for (int i = 0; i < ExcludedInsertColumns.Count; i++)
{
if (ExcludedInsertColumns[i].Trim().Length > 0)
{
excluded += "(" + Regex.Escape(ExcludedInsertColumns[i]).Replace("\\*", ".*?") + ")|";
}
}
if (excluded.Length > 0)
{
excluded = excluded.Substring(0, excluded.Length - 1);
excludedInsertColumnRegex = new Regex(excluded, RegexOptions.IgnoreCase);
}
}
}
if (excludedInsertColumnRegex != null && excludedInsertColumnRegex.IsMatch(column.Name)) return true;
return false;
}
private Regex excludedUpdateColumnRegex = null;
public bool ColumnIsExcludedUpdate(ColumnSchema column)
{
if (column.IsPrimaryKeyMember) return false;
if (excludedUpdateColumnRegex == null)
{
if (ExcludedUpdateColumns != null && ExcludedUpdateColumns.Count > 0)
{
string excluded = String.Empty;
for (int i = 0; i < ExcludedUpdateColumns.Count; i++)
{
if (ExcludedUpdateColumns[i].Trim().Length > 0)
{
excluded += "(" + Regex.Escape(ExcludedUpdateColumns[i]).Replace("\\*", ".*?") + ")|";
}
}
if (excluded.Length > 0)
{
excluded = excluded.Substring(0, excluded.Length - 1);
excludedUpdateColumnRegex = new Regex(excluded, RegexOptions.IgnoreCase);
}
}
}
if (excludedUpdateColumnRegex != null && excludedUpdateColumnRegex.IsMatch(column.Name)) return true;
return false;
}
public bool ColumnIsExcludedOrReadOnly(ColumnSchema column)
{
return ColumnIsExcluded(column) || ColumnIsReadOnly(column);
}
public bool IsExcludedInsertColumn(ColumnSchema column)
{
return ColumnIsExcludedOrReadOnly(column) || ColumnIsExcludedInsert(column);
}
public bool IsExcludedUpdateColumn(ColumnSchema column)
{
return ColumnIsExcludedOrReadOnly(column) || ColumnIsExcludedUpdate(column);
}
//----------------------------
public ColumnSchemaCollection GetColumnsByDbType(ColumnSchemaCollection columns, DbType dbType)
{
ColumnSchemaCollection collection = new ColumnSchemaCollection();
foreach(ColumnSchema column in columns)
{
if (column.DataType == dbType)
collection.Add(column);
}
return collection;
}
public IndexSchemaCollection GetNonKeyIndexes(TableSchema table)
{
IndexSchemaCollection indexes = new IndexSchemaCollection();
foreach(IndexSchema index in table.Indexes)
{
//skip primary key indexes or indexes that are placed on foreign keys
if (index.IsPrimaryKey || IndexIsForeignKey(index,table.ForeignKeys))
continue;
indexes.Add(index);
}
return indexes;
}
public IndexSchemaCollection GetUniqueIndexes(TableSchema table)
{
IndexSchemaCollection indexes = new IndexSchemaCollection();
foreach(IndexSchema index in table.Indexes)
{
//skip primary key and non-unique indexes
if (index.IsPrimaryKey || !index.IsUnique)
continue;
indexes.Add(index);
}
return indexes;
}
public ColumnSchemaCollection GetUniqueIdentifierColumns(TableSchema table)
{
ColumnSchemaCollection columns = new ColumnSchemaCollection();
foreach(ColumnSchema column in table.NonKeyColumns)
{
if (column.NativeType == "uniqueidentifier")
columns.Add(column);
}
return columns;
}
public IndexSchemaCollection GetNonUniqueIndexes(TableSchema table)
{
IndexSchemaCollection indexes = new IndexSchemaCollection();
foreach(IndexSchema index in table.Indexes)
{
//skip primary key and unique indexes as well as indexes that are foreign keys also
if (index.IsPrimaryKey || index.IsUnique || IndexIsForeignKey(index,table.ForeignKeys))
continue;
indexes.Add(index);
}
return indexes;
}
//returns ALL unique index columns
public ColumnSchemaCollection GetUniqueIndexColumns (TableSchema table)
{
ColumnSchemaCollection columns = new ColumnSchemaCollection();
foreach(IndexSchema index in this.GetUniqueIndexes(table))
{
foreach(ColumnSchema column in index.MemberColumns)
{
columns.Add(column);
}
}
return columns;
}
//Returns all indexe columns that are not unique and do not contain foreign key matches
public ColumnSchemaCollection GetNonUniqueIndexedColumns(TableSchema table)
{
ColumnSchemaCollection columns = new ColumnSchemaCollection();
foreach(IndexSchema index in this.GetNonUniqueIndexes(this.SourceTable))
{
foreach(ColumnSchema column in index.MemberColumns)
{
columns.Add(column);
}
}
return columns;
}
//returns ALL nullable date columns
public ColumnSchemaCollection GetNullableDateColumns (TableSchema table)
{
ColumnSchemaCollection columns = new ColumnSchemaCollection();
foreach(ColumnSchema column in table.Columns)
{
if (ColumnIsDate(column) && column.AllowDBNull)
{
columns.Add(column);
}
}
return columns;
}
public bool ColumnIsDate(ColumnSchema column)
{
return (
column.DataType == DbType.Date ||
column.DataType == DbType.DateTime
);
}
public bool IndexIsForeignKey(IndexSchema index, TableKeySchemaCollection fkKeySchemas)
{
bool isIdentical = false;
foreach(ColumnSchema indexColumn in index.MemberColumns)
{
foreach(TableKeySchema fkKeySchema in fkKeySchemas)
{
isIdentical = true;
foreach(ColumnSchema fkColumn in fkKeySchema.ForeignKeyMemberColumns)
{
if (!indexColumn.Equals(fkColumn))
{
isIdentical = false;
break;
}
}
if (isIdentical) break;
}
}
return isIdentical;
}
public ColumnSchemaCollection RemoveDuplicateColumns(ColumnSchemaCollection[] collections)
{
ColumnSchemaCollection columns = new ColumnSchemaCollection();
if (null != collections)
{
foreach(ColumnSchemaCollection col in collections)
{
foreach(ColumnSchema column in col)
{
if (!columns.Contains(column))
{
columns.Add(column);
}
}
}
}
return columns;
}
public bool ContainsBitColumn(ColumnSchemaCollection columns)
{
return (GetColumnsByDbType(columns,DbType.Boolean).Count > 0);
}
public bool ContainsUniqueIndex(TableSchema table)
{
ColumnSchemaCollection columns = GetUniqueIndexColumns(table);
return (null != columns && columns.Count > 0);
}
public void GenerateParametersForUpdateColumns(ColumnSchemaCollection identifierColumns, ColumnSchemaCollection updateableColumns, string newColumnNamePrefix, int indentLevel)
{
for(int i=0; i<updateableColumns.Count; i++)
{
bool found = false;
foreach(ColumnSchema identifierColumn in identifierColumns)
{//check for repeated columns!
if (updateableColumns[i].Equals(identifierColumn))
{
found = true;
break;
}
}
if (found)
{
WriteIndentedLine(this.GetSqlParameterStatementForRepeatedColumn(updateableColumns[i], newColumnNamePrefix, false, true, null), indentLevel);
//if not last add.
if (i<updateableColumns.Count-1)
Response.Write(", ");
}
else
{
this.GenerateParameter(updateableColumns[i], indentLevel, i==0, i==updateableColumns.Count-1, false);
}
}
}
public string GetSqlParameterStatementForRepeatedColumn(ColumnSchema column, string newColumnNamePrefix, bool isOutput, bool includeDefaultValue, string strDefaultValue)
{
string param = "@" + newColumnNamePrefix + column.Name + " " + column.NativeType;
switch (column.DataType)
{
case DbType.Decimal:
{
param += "(" + column.Precision + ", " + column.Scale + ")";
break;
}
case DbType.AnsiString:
case DbType.AnsiStringFixedLength:
case DbType.String:
case DbType.StringFixedLength:
{
if (column.Size > 0)
{
param += "(" + column.Size + ")";
}
break;
}
}
if (includeDefaultValue)
{
if (null != strDefaultValue)
{
param += " = " + strDefaultValue;
}
else
{
ExtendedProperty property = column.ExtendedProperties["CS_Default"];
if (null != property && null != property.Value && String.Empty != property.Value.ToString())
{
//cannot contain logical or mathematical expressions
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"['+'?]|['-'?]|['*'?]|['/'?]|['%'?]");
if (!r.IsMatch(property.Value.ToString()))
{
//remove any braces (start and end ones as well as function braces)
string s = System.Text.RegularExpressions.Regex.Replace(property.Value.ToString(), @"[\(\)]+", String.Empty);
//only add getdate!!
if (s.ToLower() == "getdate")
param += " = " + s;
}
}
}
}
if (isOutput)
{
param += " OUTPUT";
}
return param;
}
public void GenerateUpdates(ColumnSchemaCollection identifierColumns, ColumnSchemaCollection updateableColumns, string newColumnNamePrefix, int indentLevel)
{
ColumnSchemaCollection filteredColumns = FilterReadOnlyAndExcludedColumns(updateableColumns);
for(int i=0; i<filteredColumns.Count; i++)
{
bool found = false;
foreach(ColumnSchema identifierColumn in identifierColumns)
{//check for repeated columns!
if (filteredColumns[i].Equals(identifierColumn))
{
found = true;
break;
}
}
ColumnSchema column = filteredColumns[i];
GenerateIndent(indentLevel);
Response.Write("[");
Response.Write(column.Name);
Response.Write("] = @");
if (found) Response.Write(newColumnNamePrefix);
Response.Write(column.Name);
if (i<filteredColumns.Count-1) Response.Write(",");
//display key markers
//if (showKeyMarkers)
GenerateCommentedKeyMarkers(column);
if (indentLevel >= 0)
{
Response.WriteLine("");
}
else if (i<filteredColumns.Count)
{
Response.Write(" ");
}
}
}
public string GetColumnDefinition(ColumnSchema column)
{
string col = "[" + column.Name + "] ";
col += "[" + column.NativeType + "] ";
if (!IsUserDefinedType(column))
{
switch (column.DataType)
{
case DbType.Decimal:
{
col += "(" + column.Precision + ", " + column.Scale + ") ";
break;
}
case DbType.AnsiString:
case DbType.AnsiStringFixedLength:
case DbType.String:
case DbType.StringFixedLength:
{
if (column.NativeType != "text" && column.NativeType != "ntext")
{
if (column.Size > 0)
{
col += "(" + column.Size + ") ";
}
}
break;
}
}
}
if (column.AllowDBNull)
{
col += "NULL ";
}
else
{
col += "NOT NULL ";
}
return col;
}
public string GetPrimaryKeyDefinition(TableSchema table)
{
string pk;
if (table.PrimaryKey == null)
return "";
pk = "CONSTRAINT " + table.PrimaryKey.Name + " PRIMARY KEY (";
for (int i=0; i < table.PrimaryKey.MemberColumns.Count; i++)
{
if (i > 0)
pk += ", ";
pk += "[" + table.PrimaryKey.MemberColumns[i].Name + "]" ;
}
pk += ")";
return pk;
}
public void GenerateTableVariable(string name, ColumnSchemaCollection columns, int indentLevel)
{
WriteIndentedLine("DECLARE @" + name + " TABLE", indentLevel);
WriteIndentedLine("(", indentLevel);
foreach(ColumnSchema column in columns)
{
WriteIndentedLine(GetColumnDefinition(column), indentLevel+1);
}
//define primary key (cannot use constraint statement
//see http://www.aspfaq.com/show.asp?id=2475
WriteIndented("PRIMARY KEY (", indentLevel+1);
for(int i=0; i<columns.Count;i++)
{
if (columns[i].IsPrimaryKeyMember)
{
if (i>0) Response.Write(", ");
Response.Write(columns[i].Name);
}
}
Response.Write(")", indentLevel);
Response.WriteLine();
WriteIndentedLine(")", indentLevel);
}
#endregion
#region Procedure Naming
//Cleans the procedure prefix
public string GetProcedurePrefix()
{
return (null == ProcedurePrefix)? String.Empty: ProcedurePrefix.Trim();
}
//Insert Procedure
public string GetInsertProcedureName()
{
return String.Format("{0}[{1}Insert{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetInsertAllProcedureName()
{
return String.Format("{0}[{1}InsertAll{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
//Update Procedures
public string GetUpdateProcedureName()
{
return String.Format("{0}[{1}Update{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetUpdateByUniqueIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Update{2}ByUnique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetUpdateByUniqueIdentifierProcedureName(ColumnSchema column)
{
return String.Format("{0}[{1}Update{2}ByUnique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), column.Name);
}
public string GetUpdateBitColumnProcedureName()
{
return String.Format("{0}[{1}Update{2}BitColumns]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetUpdateAllProcedureName()
{
return String.Format("{0}[{1}UpdateAll{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
//Delete Procedures
public string GetDeleteProcedureName()
{
return String.Format("{0}[{1}Delete{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetDeleteAllProcedureName()
{
return String.Format("{0}[{1}DeleteAll{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetDeleteByForeignKeyProcedureName()
{
return String.Format("{0}[{1}Delete{2}ByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetDeleteByBitColumnProcedureName()
{
return String.Format("{0}[{1}Delete{2}ByBitColumn]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetDeleteByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Delete{2}By{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetDeleteByUniqueIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Delete{2}ByUnique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetDeleteByUniqueIdentifierProcedureName(ColumnSchema column)
{
return String.Format("{0}[{1}Delete{2}ByUnique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), column.Name);
}
public string GetDeleteByProcedureName()
{
return String.Format("{0}[{1}Delete{2}By]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
//Select Procedures
public string GetSelectProcedureName()
{
return String.Format("{0}[{1}Select{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectUsingOutParametersProcedureName()
{
return String.Format("{0}[{1}Select{2}UsingOutParameters]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectAllProcedureName()
{
return String.Format("{0}[{1}SelectAll{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectByForeignKeyProcedureName()
{
return String.Format("{0}[{1}Select{2}ByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectByBitColumnProcedureName()
{
return String.Format("{0}[{1}Select{2}ByBitColumn]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Select{2}By{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetSelectByUniqueIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Select{2}ByUnique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
public string GetSelectByUniqueIdentifierProcedureName(ColumnSchema column)
{
return String.Format("{0}[{1}Select{2}ByUnique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), column.Name);
}
public string GetSelectByProcedureName()
{
return String.Format("{0}[{1}Select{2}By]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchAllProcedureName()
{
return String.Format("{0}[{1}SelectSearchAll{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchByForeignKeyProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchByBitColumnProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ByBitColumn]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchByProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}By]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
//Select Unique and Primary Key
public string GetSelectUniqueIndexByPrimaryKeyProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Select{2}Unique{3}ByPrimaryKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
public string GetSelectUniqueIdentifierByPrimaryKeyProcedureName(ColumnSchema column)
{
return String.Format("{0}[{1}Select{2}Unique{3}ByPrimaryKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), column.Name);
}
public string GetSelectPrimaryKeyByUniqueIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Select{2}PrimaryKeyByUnique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
public string GetSelectPrimaryKeyByUniqueIdentifierProcedureName(ColumnSchema column)
{
return String.Format("{0}[{1}Select{2}PrimaryKeyByUnique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), column.Name);
}
//Select RowCount
public string GetSelectRowCountProcedureName()
{
return String.Format("{0}[{1}Select{2}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectRowCountByForeignKeyProcedureName()
{
return String.Format("{0}[{1}Select{2}ByForeignKeyUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectRowCountByBitColumnProcedureName()
{
return String.Format("{0}[{1}Select{2}ByBitColumnUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectRowCountByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Select{2}By{3}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetSelectRowCountByProcedureName()
{
return String.Format("{0}[{1}Select{2}ByUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchRowCountByForeignKeyProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ByForeignKeyUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchRowCountByBitColumnProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ByBitColumnUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchRowCountByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectSearch{2}By{3}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetSelectSearchRowCountByProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ByUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
//Select List
public string GetSelectListProcedureName()
{
return String.Format("{0}[{1}Select{2}List]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectListByForeignKeyProcedureName()
{
return String.Format("{0}[{1}Select{2}ListByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectListByBitColumnProcedureName()
{
return String.Format("{0}[{1}Select{2}ListByBitColumn]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectListByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Select{2}ListBy{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
public string GetSelectListByProcedureName()
{
return String.Format("{0}[{1}Select{2}ListBy]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchListProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}List]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchListByForeignKeyProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ListByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchListByBitColumnProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ListByBitColumn]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchListByProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ListBy]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectListUsingRowCountProcedureName()
{
return String.Format("{0}[{1}Select{2}ListUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectListByForeignKeyUsingRowCountProcedureName()
{
return String.Format("{0}[{1}Select{2}ListByForeignKeyUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectListByBitColumnUsingRowCountProcedureName()
{
return String.Format("{0}[{1}Select{2}ListByBitColumnUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectListByIndexUsingRowCountProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}Select{2}ListBy{3}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
public string GetSelectListByUsingRowCountProcedureName()
{
return String.Format("{0}[{1}Select{2}ListByUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchListUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ListUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchListByForeignKeyUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ListByForeignKeyUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchListByBitColumnUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ListByBitColumnUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchListByUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearch{2}ListByUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
//Select Random
public string GetSelectRandomProcedureName()
{
return String.Format("{0}[{1}SelectRandom{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectRandomUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectRandom{2}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectRandomByForeignKeyUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectRandom{2}ByForeignKeyUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectRandomByIndexUsingRowCountProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectRandom{2}By{3}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetSelectRandomByBitColumnUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectRandom{2}ByBitColumnUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectRandomByUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectRandom{2}ByUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchRandomProcedureName()
{
return String.Format("{0}[{1}SelectSearchRandom{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectSearchRandomUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearchRandom{2}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchRandomByForeignKeyUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearchRandom{2}ByForeignKeyUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchRandomByIndexUsingRowCountProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectSearchRandom{2}By{3}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetSelectSearchRandomByBitColumnUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearchRandom{2}ByBitColumnUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectSearchRandomByUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectSearchRandom{2}ByUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectRandomPrimaryKeyProcedureName()
{
return String.Format("{0}[{1}SelectRandom{2}PrimaryKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectRandomPrimaryKeyUsingRowCountProcedureName()
{
return String.Format("{0}[{1}SelectRandom{2}PrimaryKeyUsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectRandomUniqueIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectRandom{2}Unique{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
public string GetSelectRandomUniqueIndexUsingRowCountProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectRandom{2}Unique{3}UsingRowCount]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
//Select Paged
public string GetSelectPagedProcedureName()
{
return String.Format("{0}[{1}SelectPaged{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectPagedByForeignKeyProcedureName()
{
return String.Format("{0}[{1}SelectPaged{2}ByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectPagedByBitColumnProcedureName()
{
return String.Format("{0}[{1}SelectPaged{2}ByBitColumn]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectPagedByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectPaged{2}By{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetSelectPagedByProcedureName()
{
return String.Format("{0}[{1}SelectPaged{2}By]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
//Select Paged Search
public string GetSelectPagedSearchProcedureName()
{
return String.Format("{0}[{1}SelectPaged{2}Search]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectPagedSearchByForeignKeyProcedureName()
{
return String.Format("{0}[{1}SelectPaged{2}SearchByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectPagedSearchByBitColumnProcedureName()
{
return String.Format("{0}[{1}SelectPaged{2}SearchByBitColumn]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectPagedSearchByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectPaged{2}SearchBy{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
public string GetSelectPagedSearchByProcedureName()
{
return String.Format("{0}[{1}SelectPaged{2}SearchBy]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
//Select Count Procedures
public string GetSelectCountAllProcedureName()
{
return String.Format("{0}[{1}SelectCountAll{2}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectCountByForeignKeyProcedureName()
{
return String.Format("{0}[{1}SelectCount{2}ByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectCountByBitColumnProcedureName()
{
return String.Format("{0}[{1}SelectCount{2}ByBitColumn]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
public string GetSelectCountByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectCount{2}By{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(true), ConcatenateNames(columns));
}
public string GetSelectCountByProcedureName()
{
return String.Format("{0}[{1}SelectCount{2}By]", GetTableOwner(), ProcedurePrefix, GetEntityName(true));
}
//Select Count Search
public string GetSelectCountSearchProcedureName()
{
return String.Format("{0}[{1}SelectCount{2}Search]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectCountSearchByForeignKeyProcedureName()
{
return String.Format("{0}[{1}SelectCount{2}SearchByForeignKey]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectCountSearchByBitColumnProcedureName()
{
return String.Format("{0}[{1}SelectCount{2}SearchByBit]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
public string GetSelectCountSearchByIndexProcedureName(ColumnSchemaCollection columns)
{
return String.Format("{0}[{1}SelectCount{2}SearchBy{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), ConcatenateNames(columns));
}
public string GetSelectCountSearchByProcedureName()
{
return String.Format("{0}[{1}SelectCount{2}SearchBy]", GetTableOwner(), ProcedurePrefix, GetEntityName(false));
}
//Set Procedures
public string GetSetNullableDateColumnProcedureName(ColumnSchema dateColumn)
{
return String.Format("{0}[{1}Set{2}{3}]", GetTableOwner(), ProcedurePrefix, GetEntityName(false), StringUtil.ToPascalCase(dateColumn.Name));
}
//----------------------------------------------------
public string ConcatenateNames(ColumnSchemaCollection columns)
{
StringBuilder sb = new StringBuilder();
for(int i=0; i < columns.Count; i++)
{
if (i > 0) sb.Append("And");
sb.Append(StringUtil.ToPascalCase(columns[i].Name));
}
return sb.ToString();
}
public string GetEntityName(bool plural)
{
string entityName = this.SourceTable.Name;
if (null != TablePrefix)
{
if (entityName.StartsWith(TablePrefix))
{
entityName = entityName.Substring(TablePrefix.Length);
}
}
if (plural)
{
entityName = StringUtil.ToPlural(entityName);
}
else
{
entityName = ToSingular(entityName);
}
return entityName;
}
public string ToSingular(string s)
{
string tmp = s.ToLower();
char secondLastChar = tmp.ToCharArray()[tmp.Length-2];
char lastChar = tmp.ToCharArray()[tmp.Length-1];
if (secondLastChar == 'a' ||
secondLastChar == 'i' ||
secondLastChar == 'u' ||
secondLastChar == 'w')
{
//return the original name cos the word wont be a word (in most cases anyway!)
/*
Example:
1. 'i' ---> 'Analysis' cannot be 'Analysi'
2. 'u' ---> 'Status' cannot be 'Statu'
3. 'w' ---> 'News' cannot be 'New'
*/
return s;
}
/* HACKS */
string singular = StringUtil.ToSingular(s).ToLower();
if (singular == "siz")
return "Size";
return StringUtil.ToSingular(s);
}
#endregion
#region Template Overrides
// Assign an appropriate file name to the output.
public override string GetFileName()
{
if (this.SourceTable != null)
{
return this.SourceTable.Name + "_Procedures.sql";
}
else
{
return base.GetFileName();
}
}
// Override the OutputFile property and assign our specific settings to it.
[Category("02. Options")]
[FileDialog(FileDialogType.Save, Title="Select Output File", Filter="Query Files (*.sql)|*.sql|All Files (*.*)|*.*", DefaultExtension=".sql")]
public override string OutputFile
{
get {return base.OutputFile;}
set {base.OutputFile = value;}
}
protected override void OnPostRender(string result)
{
if (this.AutoExecuteScript)
{
// execute the output on the same database as the source table.
CodeSmith.BaseTemplates.ScriptResult scriptResult = CodeSmith.BaseTemplates.ScriptUtility.ExecuteScript(this.SourceTable.Database.ConnectionString, result, new System.Data.SqlClient.SqlInfoMessageEventHandler(cn_InfoMessage));
Trace.Write(scriptResult.ToString() + "\n");
}
base.OnPostRender(result);
}
private void cn_InfoMessage(object sender, System.Data.SqlClient.SqlInfoMessageEventArgs e)
{
Trace.WriteLine(e.Message);
}
#endregion
</script>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Threading.Tasks;
using Repository.Pattern.Ef6;
using Repository.Pattern.Ef6.Factories;
using Repository.Pattern.Repositories;
using MWeb.Web.UI.Repository;
using MWeb.Data.Model;
using MWeb.Data.Repository;
namespace MWeb.Web.UI.WebControls
{
///<summary>
/// Athlete Dropdown List
///</summary>
[DefaultProperty("DataTextField")]
[ToolboxData("<{0}:AthleteDropDownList runat=server></{0}:AthleteDropDownList>")]
public class AthleteDropDownList : MWeb.Web.UI.Repository.WebControls.RepositoryEntityListProviderDropDownList<Athlete, int>
{
#region Declarations
///<summary>
/// Cache Keys
///</summary>
public const string CACHE_KEY = "AthleteDropDownList-CacheKey";
#endregion
#region Constructors
///<summary>
/// Creates a <code>CustomerDropDownList</code>
///</summary>
public AthleteDropDownList()
: base()
{
//event handlers
this.Load += new System.EventHandler( this.Page_Load );
//data context.
var dataContext = new SolariEnergy.Data.Entity.SolariEnergyContext();
//setup custom repository
UnitOfWork unitOfWork = null;
var factories = new Dictionary<Type, Func<dynamic>>
{
{
typeof (AthleteRepository),
() => new AthleteRepository(dataContext, unitOfWork)
}
};
//uow & repositories.
var repositoryProvider = new RepositoryProvider( new RepositoryFactories( factories ) );
unitOfWork = new UnitOfWork( dataContext, repositoryProvider );
var repository = new AthleteRepository( dataContext, unitOfWork );
repositoryProvider.SetRepository<AthleteRepository>(repository);
//members.
this.UnitOfWork = unitOfWork;
this.Repository = repository;
}
#endregion
#region Page Events
private void Page_Load( object sender, System.EventArgs e )
{
if (!Page.IsPostBack)
{
//default sort.
this.SortBy = "OrderIndex";
this.SortDirection = MWeb.Web.UI.SortDirection.Asc;
//entity fields.
this.EntityValueField = "ProfileId";
this.EntityTextField = "ProfileId";
}
}
#endregion
#region Properties
#region GetList (Search, Filter, Include) Properties
/// <summary>
/// Returns the search expression used with <code>GetPagedList</code>
/// </summary>
public override Expression<Func<Athlete, bool>> SearchExpression
{
get
{
return
(
f => f.RepresentCountryName.Contains( this.SearchText ) ||
f.RepresentCountryIso2Code.Contains( this.SearchText ) ||
f.CoachFullName.Contains( this.SearchText ) ||
f.CoachTitle.Contains( this.SearchText ) ||
f.CoachUrl.Contains( this.SearchText ) ||
f.AgentFullName.Contains( this.SearchText ) ||
f.AgentTitle.Contains( this.SearchText ) ||
f.AgentUrl.Contains( this.SearchText ) ||
f.AgencyName.Contains( this.SearchText ) ||
f.AgencyUrl.Contains( this.SearchText ) ||
f.PersonalBests.Contains( this.SearchText )
);
}
}
/// <summary>
/// Returns the filter expression list used with <code>GetPagedList</code>
/// </summary>
public override List<Expression<Func<Athlete, bool>>> FilterExpressionList
{
get
{
if (this.IsFiltered)
{
var filterExpressionList = new List<Expression<Func<Athlete, bool>>>();
//boolean filters.
//key filters.
if (!string.IsNullOrWhiteSpace( this.ProfileId ))
{
Expression<Func<Athlete, bool>> keyFilterExp1 = (f => f.ProfileId == this.ProfileId); //ProfileId
filterExpressionList.Add( keyFilterExp1 );
}
return filterExpressionList;
}
return null;
}
}
/// <summary>
/// Returns the include expression list used with <code>GetPagedList</code>
/// </summary>
public override List<Expression<Func<Athlete, object>>> IncludeExpressionList
{
get
{
var includeExpressionList = new List<Expression<Func<Athlete, object>>>();
//Profile
Expression<Func<Athlete, object>> includeExp1 = (i => i.Profile);
includeExpressionList.Add( includeExp1 );
return includeExpressionList;
}
}
#endregion
#region Filter Properties
#region DropDownList Filter Properties
/// <summary>
/// ProfileId
/// </summary>
public int?? ProfileId
{
get
{
return (bool?)ViewState["ProfileId"];
}
set
{
if (this.ProfileId != value)
{
ViewState["ProfileId"] = value;
//set filter
this.IsFiltered = this.IsFiltered ||this.ProfileId.HasValue;
}
}
}
#endregion
#endregion
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment