Store and retrieve file with SQL Server

// Store file in SQL Server

FileStream objFileStream = new FileStream(“[Path of File]“, FileMode.Open);
byte[] Data = new byte[objFileStream.Length];
objFileStream.Read(Data, 0, Convert.ToInt32(objFileStream.Length));

SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["My"].ToString());
objConnection.Open();
SqlCommand objCommand = new SqlCommand(“Bytes_Insert”);
objCommand.Connection = objConnection;
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.Add(new SqlParameter(“@Data”, Data));
objCommand.ExecuteNonQuery();
objConnection.Close();
objFileStream.Close();

// Retrieve file from SQL Server

SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["My"].ToString());
objConnection.Open();
SqlCommand objCommand = new SqlCommand(“Bytes_ListAll”);
objCommand.Connection = objConnection;
objCommand.CommandType = CommandType.StoredProcedure;

SqlDataAdapter adpt = new SqlDataAdapter(objCommand);
DataSet ds = new DataSet();
adpt.Fill(ds);

byte[] Data = (byte[]) ds.Tables[0].Rows[0]["Data"];
File.WriteAllBytes(“[Path to store File]“, Data);

Read Excel file in Asp.Net

Read Excel file with Excel object
==================================

using Microsoft.Office.Interop.Excel;

private Excel.Application ExcelObj = null;

// Create Object with File path
Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open((Server.MapPath(“..//Data”) + “\\”
+ fu.FileName), 0, true, 5, “”, “”, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, “\t”, false, false, 0, true, true, true);

// get the collection of sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;

// get the first and only worksheet from the collection of worksheets
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);

// Loop through total row count
for (int i = 0; i < worksheet.Rows.Count; i++)
{
// Get value from ranges.
Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range(“A” + i.ToString(), “B” + i.ToString());

// In Array, You will get the cell value
System.Array myvalues = (System.Array)range.Cells.Value2;

// By Row, Column
string Value1 = myvalues.GetValue(1, 1) != null ? myvalues.GetValue(1, 1).ToString() : string.Empty;
string Value2 = myvalues.GetValue(1, 2) != null ? myvalues.GetValue(1, 2).ToString() : string.Empty;

}

Read Excel File with out Excel Object
=====================================

string strConn;
strConn = “Provider=Microsoft.Jet.OLEDB.4.0;” +
“Data Source=” + Server.MapPath(“”) + “;” +
“Extended Properties=Excel 8.0;”;
OleDbConnection con = new OleDbConnection(strConn);
con.Open();
if (con.State == ConnectionState.Open)
{

OleDbDataAdapter adp = new OleDbDataAdapter(“Select * From [test$A1:D65536]“, con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
}
con.Close()

Create and Export-Import Excel file in Asp.Net

Create and Export-Import Excel file in Asp.Net
=======================================

// This method create an Excel file and export it for download
private void CreateExcelFileandDownload()
{

try
{
// Create a new Excel file.

string[] connectStrings = new string[] {
“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\”C:\\TEMP\\TestExcel2003Output.xls\”;Extended Properties=\”Excel 8.0;HDR=Yes;\”;”,
“Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\”C:\\TEMP\\TestExcel2007Output.xlsx\”;Extended Properties=\”Excel 12.0 Xml;HDR=Yes;\”;”
};

string dropTableStmt = “DROP TABLE [test]“;
string createTableStmt = “CREATE TABLE [test] ( [Integer] int, [String] varchar(40), [Double] float, [Date] datetime, [Boolean] bit )”;
string insertStmt = “INSERT INTO [test] ([Integer], [String], [Double], [Date], [Boolean]) VALUES ({0}, ‘{1}’, {2}, ‘{3}’, {4})”;
object[] data = new object[] {

new object[] { 2628013, “Anderson”, 0.617715356, new DateTime( 2008, 5, 5 ), true },

new object[] { 2628015, “Rainaud”, 0.64933168, new DateTime( 2007, 4, 10 ), false },

new object[] { 2628017, “Dennis”, 0.62140731, new DateTime( 2006, 3, 15 ), true },

new object[] { 2628019, “Schoenster”, 0.599058708, new DateTime( 2005, 2, 20 ), false },

new object[] { 2628041, “Ganun”, 0.593402527, new DateTime( 2004, 1, 25 ), true }

};

foreach (string connect in connectStrings)
{
OleDbConnection con = new OleDbConnection(connect);
con.Open();
if (con.State == ConnectionState.Open)
{
OleDbCommand cmd = con.CreateCommand();
cmd.CommandTimeout = 0;
try
{
// Only need this on runs subsequent to first time
cmd.CommandText = dropTableStmt;
cmd.ExecuteNonQuery();
}
catch
{
// First run will cause exception because table (worksheet) doesn’t exist
}

cmd.CommandText = createTableStmt;
cmd.ExecuteNonQuery();
foreach (object[] row in data)
{
cmd.CommandText = String.Format(insertStmt, row[0], row[1], row[2], row[3], row[4]);
cmd.ExecuteNonQuery();
}

cmd.Dispose();
if (con.State == ConnectionState.Open)
con.Close();
con.Dispose();
}
}

// Download Created File

// For Office 2007 format
string FileName = @”C:\TEMP\TestExcel2007Output.xlsx”;
// For Office 97 – 2003 format
string FileName2 = @”C:\TEMP\TestExcel2003Output.xls”;

Response.Clear();
Response.ClearContent();
Response.ContentType = “application/vnd.xls”;
Response.AddHeader(“Content-Disposition”, “attachment; filename=Name.xlsx;”);

byte[] buffer = System.IO.File.ReadAllBytes(FileName);

System.IO.MemoryStream mem = new System.IO.MemoryStream();
mem.Write(buffer, 0, buffer.Length);

mem.WriteTo(Response.OutputStream);
Response.End();
}
catch (Exception ex)
{
// throw an exception
}

}

Use Custom paging for DataList, GridView in Asp.Net

Use Custom paging for Datalist, GridView in Asp.Net
=============================================

Suppose your HTML layout is like;
——————————————

// Stylesheet
/* Start Pager 2 style */
.Pager2 { border-collapse:collapse;}
.Pager2 a { color:#0080C0; font-weight:bold; margin:1px; padding:2px 5px; border:1px solid white; text-decoration:none }
.Pager2 a:hover { color:White; font-weight:bold; border:1px #0080C0 solid; background-color:#0080C0 }
.Pager2 span { margin:1px; padding:2px 5px; background-color:#0080C0; color:White; border:1px #0080C0 solid}
/* End Pager 2 style */

// Page HTML layout
<div>
Name : <asp:TextBox ID=”txtName” runat=”server”></asp:TextBox> <asp:Button ID=”btnGo” runat=”server” Text=”Go” OnClick=”btnGo_Click” />

<asp:DataList ID=”dlCompanylist” RepeatColumns=”1″ RepeatDirection=”Horizontal” runat=”server”>
<ItemTemplate>
<table width=”200px” cellpadding=”1″ cellspacing=”1″ style=”border-collapse:collapse”>
<tr>
<td valign=”top” style=”width:100px”>ID :</td>
<td><%#Eval(“ID”).ToString() %></td>
</tr>
<tr>
<td valign=”top” >Name</td><td><%#Eval(“Name”).ToString() %>
</td>
</tr>
<tr>
<td valign=”top”>Date</td>
<td><%#Eval(“RegisterDate”).ToString() %></td>
</tr>
<tr>
<td colspan=”2″ style=”border-bottom:solid 1px gray”> </td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<br />
<asp:Literal ID=”ltPaging” runat=”server”></asp:Literal>
</div>

// Javascript Method
<script language=”javascript” type=”text/javascript”>

function next_prev_page(val)
{

location.href = “zzCustomPaging.aspx?page=” + val;

}
</script>

// Code Behind Part
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}

private void BindGrid()
{
Company objCompany = new Company();

objCompany.name = txtName.Text.Trim();
objCompany.status = 3;
objCompany.SortBy = “Name”;
objCompany.SortOrder = SortDirection.Ascending;
objCompany.PageNo = Request.QueryString["Page"] != null ? int.Parse(Request.QueryString["Page"].ToString()) – 1 : 0;
objCompany.PageSize = 5;

DataSet dsCompanyList = objCompany.GetCompanyRegisterListAll();

if (dsCompanyList != null && dsCompanyList.Tables[0].Rows.Count > 0)
{
dlCompanylist.DataSource = dsCompanyList.Tables[0];
dlCompanylist.DataBind();

ltPaging.Text = this.Paging(objCompany.PageNo + 1, int.Parse(dsCompanyList.Tables[1].Rows[0][0].ToString()), objCompany.PageSize);
}
}

private string Paging(int Page, int TotalRecords, int PageSize)
{
int PageNo = 0;
string NextPage = “”;
string PreviousPage = “”;
string Print = “”;
string Range = “”;
string Pager = “”;

int Start = 0;
int StartRange = 0;
int EndRange = 0;

if (TotalRecords > PageSize)
{
double RecordForPaging = Math.Ceiling((Convert.ToDouble(TotalRecords) / Convert.ToDouble(PageSize)));
double RecordPage, v;
int NewNo;

if (RecordForPaging > Math.Floor(RecordForPaging))
{
RecordPage = (Math.Floor(RecordForPaging)) + 1;
}
else
{
RecordPage = RecordForPaging;
}

if (RecordPage <= PageSize)
v = RecordPage;
else
v = 5;

if (Page != 1)
PreviousPage = “<div class=’Pager2′><a href=javascript:next_prev_page(” + (Page – 1) + “);>PREVIOUS</a></div>”;
else
PreviousPage = “”;

if (Page != RecordPage)
NextPage = “<div class=’Pager2′><a href=javascript:next_prev_page(” + (Page + 1) + “);>NEXT</a></div>”;

Print = “”;

if (Page == 1)
{
for (PageNo = 1; PageNo <= v; PageNo++)
{
if (RecordPage >= PageNo)
{
if (PageNo == Page)
{
Print += ” <b class=’Pager2′><span>” + PageNo + “</span></b>”;
}
else
{
Print += ” <b class=’Pager2′><a href=javascript:next_prev_page(” + PageNo + “);>” + PageNo + “</a></b>”;
}
}
}
}
else if (Page <= RecordPage)
{
if (PageNo <= RecordPage)
NewNo = 2;
else
NewNo = Page – 5;

if (PageNo <= RecordPage)
NewNo = Page – 5;

for (PageNo = NewNo; PageNo <= Page + 5; PageNo++)
{
if (PageNo > 0)
{
if (PageNo == Page)
Print += ” <b class=’Pager2′><span>” + PageNo + “</span></b>”;
else
{
if (PageNo <= RecordPage)
Print += ” <b class=’Pager2′><a href=javascript:next_prev_page(” + PageNo + “);>” + PageNo + “</a></b>”;
}
}
}
}

Start = (Page – 1) * PageSize;
StartRange = Start + 1;
EndRange = Start + PageSize;

if (EndRange >= TotalRecords)
EndRange = TotalRecords; //end display
Range = StartRange + “-” + EndRange + ” of ” + TotalRecords;
Pager = “<table width=’100%’ border=’0′ style=’border-collapse:collapse’ ><tr><TD ALIGN=’right’ width=’20%’><TABLE border=’0′><TR>”;
Pager += “<td width=’70px’>” + PreviousPage + “</td><td NOWRAP width=’200px’> <div>” + Print + ” </div></td><td NOWRAP width=’70px’ align=’left’>” + NextPage + “</td>”;
Pager += “</TR></TABLE></TD><td WIDTH=’80%’ ><div align=’left’>” + Range + “</div></td>”;
Pager += “</td></tr></table>”;
return Pager;
}

return string.Empty;
}

That’s It !
Hope you will like it.

Use Dynamic stylesheet class for messages in Asp.Net

Hi,

In the web application, some times we need to use a message style for
only one Label, like, suppose if our data has been added successfully, we display
message like ‘Records has been added successfully’. So, depend on
system’s different situation, we have to display label message with style color
combination.

So, Here you can find the solution. By it, you can display your message
with sytle as per your system’s situation.

Just copy and paste the style script and copy C# method in your page.

You can find it here…

<style type=”text/css”>

.MessageSuccess
{
background: #EFF4EA url(images/icn_successful.gif) center no-repeat;
background-position: 15px 5px; /* x-pos y-pos */
font-weight:bold;
text-align: left;
padding: 5px 20px 5px 45px;
border-top: 1px solid #1E8B18;
border-bottom: 1px solid #1E8B18;
color:#555555;

}
.MessageInfo
{
background: #FFFFD2 url(images/icn_info.gif) center no-repeat;
background-position: 15px 5px; /* x-pos y-pos */
text-align: left;
font-weight:bold;
padding: 5px 20px 5px 45px;
border-top: 1px solid #CACA00;
border-bottom: 1px solid #CACA00;
color:#555555;

}
.MessageError
{
background: #FFEAEA url(images/icn_error.gif) center no-repeat;
background-position: 15px 5px; /* x-pos y-pos */
text-align: left;
font-weight:bold;
padding: 5px 20px 5px 45px;
border-top: 1px solid #FF6F6F;
border-bottom: 1px solid #FF6F6F;
color:#555555;

}
</style>

(Download these images for stylesheet)


<form id=”form1″ runat=”server”>
<asp:Label ID=”lblMessage” runat=”server” />
</form>

protected void Page_Load(object sender, EventArgs e)
{
lblMessage.Text = “Records has been Added Successfully.”;
this.SetStyle(lblMessage, MessageType.Info);
}

private void SetStyle(Label objLabel, MessageType msgType)
{
if (string.IsNullOrEmpty(objLabel.Text.Trim()))
objLabel.CssClass = “”;
else
{
switch (msgType)
{
case MessageType.Error:
objLabel.CssClass = “MessageError”;
break;
case MessageType.Info:
objLabel.CssClass = “MessageInfo”;
break;
case MessageType.Success:
objLabel.CssClass = “MessageSuccess”;
break;
}
}
}

// Define enum in the outer side of your page class.
public enum MessageType
{
Success,
Info,
Error
}

Now, Run your page and check it.

That’s it !
Hope you will lie it.

Remove HTML string – tag from specified string.

Remove HTML string – tag from specified string.
========================================

using System.Text.RegularExpressions;

public static string RemoveHtml(string strSource)
{

string pattern = @”";

strSource = Regex.Replace(strSource, pattern, string.Empty);

return strSource;
}

That’s It !!
Hope you will like it.

How to use Custom Validator in Asp.Net

How to use Custom Validator in Asp.Net
—————————————————

This is the HTML section of Custom Validator Control.

<asp:CustomValidator ID=”custVal” runat=”Server” ValidationGroup=”grpProductAdd”
Display=”None” ErrorMessage=”Please, Enter Product Amount.” ClientValidationFunction=”CheckProduct”>
</asp:CustomValidator>

We need a javascript function to use Custom Validation that return either ‘true’ or ‘false’ result.

<script language=”javascript” type=”text/javascript”>

// You must use this both parameter with your function, because by it Validator validate the result.
function CheckProduct(sender, args)
{
// This is the variable name by which we can identify true/false result.
var Check = 0;

var ProductVal = document.getElementById(‘txtProductVal’).value;
if (ProductVal = ”)
{
Check = 0
}
else
{
Check = 1
}

// If your condition become true
if (Check == ‘0′ )
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
</script>

That’s It !
Hope you will like it.

Javascript to dynamically add styles and event to form Element.

Javascript to dynamically add styles and event to form Element
=====================================================

<HTML>
<HEAD>

<style type=”text/css”>
.OnFocus
{
background-color : gray;
}
.OnBlur
{
background-color : white;
}
</style>

<script language=”javascript” type=”text/javascript”>

function SetStyle()
{
var elem = document.getElementById(‘frmMain’).elements;

for(var i = 0; i < elem.length; i++)
{
// Assing style to each and every textbox on this page.
if (elem[i].type == “text”)
{
elem[i].setAttribute(“onfocus”,”this.className = ‘OnFocus’;”);
elem[i].setAttribute(“onblur”,”this.className = ‘OnBlur’;”);
}
}
}

</script>
</HEAD>

<BODY onload=”javascript:SetStyle()”>
<form id=”frmMain” >

<input type=”text” value=”Hello 1″ id=”text1″ /> <br/>
<input type=”text” value=”Hello 1″ id=”text2″ /><br/>
<input type=”password” value=”Hello 1″ id=”text1″ /> <br/>

</form>
</BODY>
</HTML>

That’s It !
Hope you will like it.

How to create Image reflection in Asp.Net

How to create Image reflection in Asp.Net
=======================================

Method :
———

public Image DrawReflection(Image _Image, Color _BackgroundColor, int _Reflectivity)
{
// Calculate the size of the new image
int height = (int)(_Image.Height + (_Image.Height * ((float)_Reflectivity / 255)));
Bitmap newImage = new Bitmap(_Image.Width, height, PixelFormat.Format24bppRgb);
newImage.SetResolution(_Image.HorizontalResolution, _Image.VerticalResolution);

using (Graphics graphics = Graphics.FromImage(newImage))
{
// Initialize main graphics buffer
graphics.Clear(_BackgroundColor);
graphics.DrawImage(_Image, new Point(0, 0));
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle destinationRectangle = new Rectangle(0, _Image.Size.Height, _Image.Size.Width, _Image.Size.Height);

// Prepare the reflected image
int reflectionHeight = (_Image.Height * _Reflectivity) / 255;
Image reflectedImage = new Bitmap(_Image.Width, reflectionHeight);

// Draw just the reflection on a second graphics buffer
using (Graphics gReflection = Graphics.FromImage(reflectedImage))
{
gReflection.DrawImage(_Image, new Rectangle(0, 0, reflectedImage.Width, reflectedImage.Height),
0, _Image.Height – reflectedImage.Height, reflectedImage.Width, reflectedImage.Height, GraphicsUnit.Pixel);
}
reflectedImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
Rectangle imageRectangle = new Rectangle(destinationRectangle.X, destinationRectangle.Y,
destinationRectangle.Width, (destinationRectangle.Height * _Reflectivity) / 255);

// Draw the image on the original graphics
graphics.DrawImage(reflectedImage, imageRectangle);

// Finish the reflection using a gradiend brush
LinearGradientBrush brush = new LinearGradientBrush(imageRectangle,
Color.FromArgb(255 – _Reflectivity, _BackgroundColor),
_BackgroundColor, 90, false);
graphics.FillRectangle(brush, imageRectangle);
}

return newImage;
}

How to Use It (Testing)
—————————–

Response.ContentType = “image/jpeg”;

Image objImage = Image.FromFile(Server.MapPath(“Image.jpg”));

Image objImage2 = this.DrawReflection(objImage, Color.White, 80);

objImage2.Save(Response.OutputStream, ImageFormat.Jpeg);

That’s it !
Hope you will like it.

How to create Insert Script in SQL Server database

How to create Insert Script in SQL Server database
===========================================

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

)
AS
BEGIN

/***********************************************************************************************************

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

Example 1: To generate INSERT statements for table ‘titles’:

EXEC sp_generate_inserts ‘titles’

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

EXEC sp_generate_inserts ‘titles’, @include_column_list = 0

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

EXEC sp_generate_inserts ‘titles’, ‘titlesCopy’

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

EXEC sp_generate_inserts ‘titles’, @from = “from titles where title like ‘%Computer%’”

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

EXEC sp_generate_inserts ‘titles’, @include_timestamp = 1

Example 6: To print the debug information:

EXEC sp_generate_inserts ‘titles’, @debug_mode = 1

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

EXEC sp_generate_inserts Nickstable, @owner = ‘Nick’

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

EXEC sp_generate_inserts imgtable, @ommit_images = 1

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

EXEC sp_generate_inserts mytable, @ommit_identity = 1

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

EXEC sp_generate_inserts mytable, @top = 10

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

EXEC sp_generate_inserts titles, @cols_to_include = “‘title’,'title_id’,'au_id’”

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

EXEC sp_generate_inserts titles, @cols_to_exclude = “‘title’,'title_id’,'au_id’”

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

EXEC sp_generate_inserts titles, @disable_constraints = 1

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

SET NOCOUNT ON

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

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

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

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

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

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

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

–Variable Initialization
SET @IDN = ”
SET @Column_ID = 0
SET @Column_Name = ”
SET @Column_List = ”
SET @Actual_Values = ”

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

–To get the first column’s ID

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

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

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

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

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

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

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

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

–Generating the column list for the INSERT statement
SET @Column_List = @Column_List + @Column_Name + ‘,’

SKIP_LOOP: –The label used in GOTO

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

–Loop ends here!
END

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

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

–Forming the final string that will be executed, to output the INSERT statements
IF (@include_column_list <> 0)
BEGIN
SET @Actual_Values =
‘SELECT ‘ +
CASE WHEN @top IS NULL OR @top < 0 THEN ” ELSE ‘ TOP ‘ + LTRIM(STR(@top)) + ‘ ‘ END +
”” + RTRIM(@Start_Insert) +
‘ ”+’ + ”’(‘ + RTRIM(@Column_List) + ”’+’ + ”’)”’ +
‘ +”VALUES(”+ ‘ + @Actual_Values + ‘+”)”’ + ‘ ‘ +
COALESCE(@from,’ FROM ‘ + CASE WHEN @owner IS NULL THEN ” ELSE ‘[' + LTRIM(RTRIM(@owner)) + '].’ END + ‘[' + rtrim(@table_name) + ']‘ + ‘(NOLOCK)’)
END
ELSE IF (@include_column_list = 0)
BEGIN
SET @Actual_Values =
‘SELECT ‘ +
CASE WHEN @top IS NULL OR @top < 0 THEN ” ELSE ‘ TOP ‘ + LTRIM(STR(@top)) + ‘ ‘ END +
”” + RTRIM(@Start_Insert) +
‘ ” +”VALUES(”+ ‘ + @Actual_Values + ‘+”)”’ + ‘ ‘ +
COALESCE(@from,’ FROM ‘ + CASE WHEN @owner IS NULL THEN ” ELSE ‘[' + LTRIM(RTRIM(@owner)) + '].’ END + ‘[' + rtrim(@table_name) + ']‘ + ‘(NOLOCK)’)
END

–Determining whether to ouput any debug information
IF @debug_mode =1
BEGIN
PRINT ‘/*****START OF DEBUG INFORMATION*****’
PRINT ‘Beginning of the INSERT statement:’
PRINT @Start_Insert
PRINT ”
PRINT ‘The column list:’
PRINT @Column_List
PRINT ”
PRINT ‘The SELECT statement executed to generate the INSERTs’
PRINT @Actual_Values
PRINT ”
PRINT ‘*****END OF DEBUG INFORMATION*****/’
PRINT ”
END

PRINT ‘–INSERTs generated by ‘’sp_generate_inserts” stored procedure written by Vyas’
PRINT ‘–Build number: 22′
PRINT ‘–Problems/Suggestions? Contact Vyas @ vyaskn@hotmail.com’
PRINT ‘–http://vyaskn.tripod.com’
PRINT ”
PRINT ‘SET NOCOUNT ON’
PRINT ”

–Determining whether to print IDENTITY_INSERT or not
IF (@IDN <> ”)
BEGIN
PRINT ‘SET IDENTITY_INSERT ‘ + QUOTENAME(COALESCE(@owner,USER_NAME())) + ‘.’ + QUOTENAME(@table_name) + ‘ ON’
PRINT ‘GO’
PRINT ”
END

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

PRINT ‘GO’
END

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

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

PRINT ‘PRINT ”Done”’
PRINT ”

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

PRINT ‘GO’
END

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

PRINT ‘SET NOCOUNT OFF’

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