Saturday, November 25, 2017

Check the existence of Entities and their structure in SQL Server

1. Check If Column Exists in Table:
IF EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'columnName'
          AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
    -- Column Exists
END


2. Check If Table Exists
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_NAME = N'Customers')
BEGIN
  PRINT 'Table Exists'
END


3. Check If Stored Procedure Exists in SQL
IF EXISTS ( SELECT *
            FROM   sysobjects
            WHERE  id = object_id(N'[dbo].[MyProc]')
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    --DROP PROCEDURE [dbo].[MyProc]
END

4. Check If User-Defined Function Exists in SQL
IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
Begin
  --DROP FUNCTION [dbo].[foo]
End

GO 

Thursday, November 23, 2017

Register AutoMapper using UnityConfig .Net Web API 2

AutoMapper:  
Assembly AutoMapper, Version=6.2.1.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005

UnitConfig.cs

var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new CommonMappingProfile());
            }); 

 var container = new UnityContainer();
container.RegisterInstance(config.CreateMapper());

Wednesday, September 6, 2017

SQL: Get Distance from 2 Lat-Long pairs.

Declare @T1 GEOGRAPHY,@T2 GEOGRAPHY;
Select @T1= GEOGRAPHY::Point('42.372', '-71.0298', 4326) --Boston
,@T2=GEOGRAPHY::Point('41.953', '-87.643', 4326) --Chicago
Select @T1.STDistance(@T2) As 'Distane in Meters' ,@T1.STDistance(@T2) / 1000 As 'Distane in KM'

Sunday, August 20, 2017

Serialize Specific Properties of List using Newtonsoft.Json in .Net C#


/* Custom ContractResolver: The below contract resolver will help to serialize only those properties that will be defined in the resolver settings*/

public class DynamicContractResolver : DefaultContractResolver
    {
        private readonly List<string> _propertiesToSerialize;
        public DynamicContractResolver(string propertiesToSerialize = "")
        {
            var list = !string.IsNullOrEmpty(propertiesToSerialize) ? propertiesToSerialize.Split(',').ToList() : new List<string>();
            _propertiesToSerialize = list;
        }

        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var properties = base.CreateProperties(type, memberSerialization);
            properties = properties.Where(p => _propertiesToSerialize.Contains(p.PropertyName.ToLower())).ToList();
            return properties;
        }
    }



/* Entity */
public class TestClass
{
public int Id {get;set;}
public string Name {get;set;}
public string Age {get;set;}
}


/*
var list = new List<TestClass>();
list.Add(new TestClass { Id=1, Name ="Amit Jain",Age="31"});
list.Add(new TestClass { Id=2, Name ="Michael",Age="25"});
list.Add(new TestClass { Id=3, Name ="Robin",Age="26"});
*/


Now, Lets try to serialize only Name and Age:

Note: TO use below, one must include the Newtonsoft.Json reference into the project.

var data = JsonConvert.SerializeObject(list, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver("name,age") });


/* Here's the output of the Data String as Json*/

[
  {
    "Name": "Amit Jain",
    "Age": 31
  },
  {
    "Name": "Michael",
    "Age": 25
  },
  {
    "Name": "Robin",
    "Age": 26
  }
]


Try it..












Parse Json String and then convert rows to columns (in SQL Server 2014 or previous versions)



---User Defined Function
/*Create  One Customized Function to parse Json String to tabular form in SQL Server */


IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[parseJSON]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[parseJSON]

Go

CREATE FUNCTION dbo.parseJSON(@JSON NVARCHAR(MAX))
RETURNS @hierarchy TABLE
 (
  element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
  sequenceNo [int] NULL, /* the place in the sequence for the element */
  parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
  Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
  NAME NVARCHAR(2000),/* the name of the object */
  StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
  ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
 )
AS
BEGIN
 DECLARE
   @FirstObject INT, --the index of the first open bracket found in the JSON string
   @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
   @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
   @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
   @Type NVARCHAR(10),--whether it denotes an object or an array
   @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
   @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
   @Start INT, --index of the start of the token that you are parsing
   @end INT,--index of the end of the token that you are parsing
   @param INT,--the parameter at the end of the next Object/Array token
   @EndOfName INT,--the index of the start of the parameter at end of Object/Array token
   @token NVARCHAR(200),--either a string or object
   @value NVARCHAR(MAX), -- the value as a string
   @SequenceNo int, -- the sequence number within a list
   @name NVARCHAR(200), --the name as a string
   @parent_ID INT,--the next parent ID to allocate
   @lenJSON INT,--the current length of the JSON String
   @characters NCHAR(36),--used to convert hex to decimal
   @result BIGINT,--the value of the hex symbol being parsed
   @index SMALLINT,--used for parsing the hex value
   @Escape INT --the index of the next escape character
 
 DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
   (
    String_ID INT IDENTITY(1, 1),
    StringValue NVARCHAR(MAX)
   )
 SELECT--initialise the characters to convert hex to ascii
   @characters='0123456789abcdefghijklmnopqrstuvwxyz',
   @SequenceNo=0, --set the sequence no. to something sensible.
 /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
   @parent_ID=0;
 WHILE 1=1 --forever until there is nothing more to do
   BEGIN
     SELECT
       @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
     IF @start=0 BREAK --no more so drop through the WHILE loop
     IF SUBSTRING(@json, @start+1, 1)='"'
       BEGIN --Delimited Name
         SET @start=@Start+1;
         SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
       END
     IF @end=0 --no end delimiter to last string
       BREAK --no more
     SELECT @token=SUBSTRING(@json, @start+1, @end-1)
     --now put in the escaped control characters
     SELECT @token=REPLACE(@token, FROMString, TOString)
     FROM
       (SELECT
         '\"' AS FromString, '"' AS ToString
        UNION ALL SELECT '\\', '\'
        UNION ALL SELECT '\/', '/'
        UNION ALL SELECT '\b', CHAR(08)
        UNION ALL SELECT '\f', CHAR(12)
        UNION ALL SELECT '\n', CHAR(10)
        UNION ALL SELECT '\r', CHAR(13)
        UNION ALL SELECT '\t', CHAR(09)
       ) substitutions
     SELECT @result=0, @escape=1
 --Begin to take out any hex escape codes
     WHILE @escape>0
       BEGIN
         SELECT @index=0,
         --find the next hex escape sequence
         @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
         IF @escape>0 --if there is one
           BEGIN
             WHILE @index<4 --there are always four digits to a \x sequence
               BEGIN
                 SELECT --determine its value
                   @result=@result+POWER(16, @index)
                   *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
                               @characters)-1), @index=@index+1 ;
     
               END
               -- and replace the hex sequence by its unicode value
             SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
           END
       END
     --now store the string away
     INSERT INTO @Strings (StringValue) SELECT @token
     -- and replace the string with a token
     SELECT @JSON=STUFF(@json, @start, @end+1,
                   '@string'+CONVERT(NVARCHAR(5), @@identity))
   END
 -- all strings are now removed. Now we find the first leaf.
 WHILE 1=1  --forever until there is nothing more to do
 BEGIN

 SELECT @parent_ID=@parent_ID+1
 --find the first object or list by looking for the open bracket
 SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
 IF @FirstObject = 0 BREAK
 IF (SUBSTRING(@json, @FirstObject, 1)='{')
   SELECT @NextCloseDelimiterChar='}', @type='object'
 ELSE
   SELECT @NextCloseDelimiterChar=']', @type='array'
 SELECT @OpenDelimiter=@firstObject
 WHILE 1=1 --find the innermost object or list...
   BEGIN
     SELECT
       @lenJSON=LEN(@JSON+'|')-1
 --find the matching close-delimiter proceeding after the open-delimiter
     SELECT
       @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
                                     @OpenDelimiter+1)
 --is there an intervening open-delimiter of either type
     SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
            RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
     IF @NextOpenDelimiter=0
       BREAK
     SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
     IF @NextCloseDelimiter<@NextOpenDelimiter
       BREAK
     IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
       SELECT @NextCloseDelimiterChar='}', @type='object'
     ELSE
       SELECT @NextCloseDelimiterChar=']', @type='array'
     SELECT @OpenDelimiter=@NextOpenDelimiter
   END
 ---and parse out the list or name/value pairs
 SELECT
   @contents=SUBSTRING(@json, @OpenDelimiter+1,
                       @NextCloseDelimiter-@OpenDelimiter-1)
 SELECT
   @JSON=STUFF(@json, @OpenDelimiter,
               @NextCloseDelimiter-@OpenDelimiter+1,
               '@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
 WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
   BEGIN
     IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
       BEGIN
         SELECT
           @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
         SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
         SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
           @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
           @param=RIGHT(@token, LEN(@token)-@endofname+1)
         SELECT
           @token=LEFT(@token, @endofname-1),
           @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
         SELECT  @name=stringvalue FROM @strings
           WHERE string_id=@param --fetch the name
       END
     ELSE
       SELECT @Name=null,@SequenceNo=@SequenceNo+1
     SELECT
       @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
     IF @end=0
       SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)
         +1
      SELECT
       @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)
     --select @start,@end, LEN(@contents+'|'), @contents
     SELECT
       @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
       @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
     IF SUBSTRING(@value, 1, 7)='@object'
       INSERT INTO @hierarchy
         (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
         SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
           SUBSTRING(@value, 8, 5), 'object'
     ELSE
       IF SUBSTRING(@value, 1, 6)='@array'
         INSERT INTO @hierarchy
           (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
           SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
             SUBSTRING(@value, 7, 5), 'array'
       ELSE
         IF SUBSTRING(@value, 1, 7)='@string'
           INSERT INTO @hierarchy
             (NAME, SequenceNo, parent_ID, StringValue, ValueType)
             SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
             FROM @strings
             WHERE string_id=SUBSTRING(@value, 8, 5)
         ELSE
           IF @value IN ('true', 'false')
             INSERT INTO @hierarchy
               (NAME, SequenceNo, parent_ID, StringValue, ValueType)
               SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
           ELSE
             IF @value='null'
               INSERT INTO @hierarchy
                 (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                 SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
             ELSE
               IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
                 INSERT INTO @hierarchy
                   (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                   SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
               ELSE
                 INSERT INTO @hierarchy
                   (NAME, SequenceNo, parent_ID, StringValue, ValueType)
                   SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
     if @Contents=' ' Select @SequenceNo=0
   END
 END
INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
 SELECT '-',1, NULL, '', @parent_id-1, @type
--
  RETURN
END
GO


Here's is the Catch:


Declare @T2 Table (Id int, F1 nvarchar(max), F2 nvarchar(max))
Declare @JsonData nvarchar(MAX)='[{"FileName1":"Koala.jpg","FilePath":"\/Content\/Images\/ProfileImages\/2\/Koala.jpg"},{"FileName1":"Chrysanthemum.jpg","FilePath":"\/Content\/Images\/ProfileImages\/2\/Chrysanthemum.jpg"}]'

Delete From @T2
INSERT INTO @T2
select Id,StringValue ,[Name]
  from (
 Select row_number() over (partition by [Name] order by [Name]) As Id, * From dbo.parseJSON(@JsonData)
Where [Name] IN ('FileName1','FilePath')
  ) dd

  declare @pivot_columns nvarchar(max), @stmt nvarchar(max)

 --Select * From @T2

select
    @pivot_columns =
    isnull(@pivot_columns + ', ', '') +
    '[' +  F2 + ']'
from (select distinct F2 from @T2) as T

--Select @pivot_columns

select *
from @T2 as t1
pivot
(
min(F1)
for F2 in ([FileName1], [FilePath])
) as PT











Friday, July 21, 2017

Check the Data Type plus other details of each column in the Stored Procedure Result in SQL Server

//Shows the list of each column with details, that are returned from the Stored Procedure in SQL Server

For instance, there is Stored Procedure SprocGetUsersList. Now, if User wants to see the data type of each column in the list returned from that Proc, here's solution:

SELECT p.name, r.*
FROM sys.procedures AS p
CROSS APPLY sys.dm_exec_describe_first_result_set_for_object(p.object_id, 0) AS r
where p.name='SprocGetUsersList';
GO


Compatibility:
yesSQL Server (starting with 2012)yesAzure SQL Database


References: 

https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-describe-first-result-set-for-object-transact-sql


Friday, June 30, 2017

Post Updated values only, using Entity Framework C#

Scenario:
What if One wants to update the values from new model to an existing Entity.

E.g. We have User Entity as follows:

Public class User
{
 public long Id { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
}

/*************** OLD APPROACH *********************/

Update(user updatedUser)
{
var model = context.Users.Where(u => u.Id == Id).FirstOrDefault();
if(model !=null)
{
model.FirstName =updatedUser.FirstName;
model.LastName =updatedUser.LastName;

context.Users.Update(model);
await context.SaveChangesAsync();
}
}



/*************** BETTER APPROACH *********************/


//Generic Method
/// <summary>
        /// This function actually updates the properties of 'target' object based on the values in the 'Source' Object, with the condition: Both Objects must have same type
        /// </summary>
        /// <typeparam name="T">The Generic Entity</typeparam>
        /// <param name="source">The current Object having new Values</param>
        /// <param name="target">The current Object to which new values are to be updated</param>
        public static void CopyValues<T>(T source, T target)
        {
            Type t = typeof(T);

            var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);

            foreach (var prop in properties)
            {
                var value = prop.GetValue(source, null);
                if (value != null)
                    prop.SetValue(target, value, null);
            }
        }

//Update Method

Update(user updatedUser)
{
var model = context.Users.Where(u => u.Id == Id).FirstOrDefault();
if(model !=null)
{
model.FirstName =updatedUser.FirstName;
model.LastName =updatedUser.LastName;

CopyValues(updatedUser,model);

context.Users.Update(model);
await context.SaveChangesAsync();
}
}


Happy Coding!!













Friday, May 5, 2017

Convert different Date format to the SQL Acceptable one.

Declare @DateTimeValue nvarchar(100)= '03/01/2017 13:15'


--Date Value
SELECT CONVERT(CHAR(10),CONVERT(DATETIME,LEFT(@DateTimeValue,10),105),101);

--Date Time Value
Select Cast(CONVERT(VARCHAR(24), CONVERT(DATETIME, max(@DateTimeValue), 103), 101)+' '+ CONVERT(VARCHAR(5), CONVERT(DATETIME, max(@DateTimeValue), 103), 108) as datetime)

Thursday, May 4, 2017

SQL: Trimming all the column values using LTRIM and RTRIM dynamically

The below SQL Dynamic Query will remove all the white spaces from each column of datatype varchar or nvarchar using LTRIM and RTRIM.

DECLARE @SQL VARCHAR(MAX)
DECLARE @TableName NVARCHAR(128)
SET @TableName = 'Users'

SELECT @SQL = COALESCE(@SQL + ',[', '[') +
              COLUMN_NAME + ']=LTRIM(RTRIM([' + COLUMN_NAME + ']))'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
    AND (DATA_TYPE = 'varchar' OR DATA_TYPE = 'nvarchar')

SET @SQL = 'UPDATE [' + @TableName + '] SET ' + @SQL

PRINT @SQL
EXEC(@SQL)


Tuesday, April 4, 2017

Display basic time value (in 12-hours format) using jquery in .Net Web Apps.

Design view (.cshtml Razor View where the div was taken to show the time value)

@{
                        DateTime dt = DateTime.Now;
                        var time = dt.ToString("hh:mm tt");
                        var tArr = time.Split(' ');
                    }

<div class="date_time">
                       @* Displaying the date value *@
                        <div class="date" id="divDateOnly"><i class="fa fa-calendar" aria-hidden="true"></i>@dt.ToString("MMM - dd - yyyy")</div>

                       @* Displaying the time value and this needs to be refreshed every second. *@
                        <div class="time" id="divTimeOnly"><i class="fa fa-clock-o" aria-hidden="true"></i>@tArr[0]<sub>@tArr[1]</sub></div>
</div>


/* function to convert the date to time value in 12-hour format */
function formatAMPM(date) {
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var ampm = hours >= 12 ? 'pm' : 'am';
            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'
            hours = hours < 10 ? '0'+ hours : hours;
            minutes = minutes < 10 ? '0'+ minutes : minutes;
            var strTime = hours + ':' + minutes + ' ' + ampm;
            return strTime;
        }

/* set the interval at 1 second at document ready function */
$(document).ready(function(){
     setInterval(function() {
                var d = new Date();
                var monthName = monthNames[d.getMonth()];
                var day = d.getDate();
                var year = d.getFullYear();
                var time = formatAMPM(d);
                var tArray = time.split(' ');
                console.log(time);
                $("#divTimeOnly").html('<i class="fa fa-clock-o" aria-hidden="true"></i>' + tArray[0] +                      '<sub>' + tArray[1] + '</sub>');
                },1000);
});

Sunday, March 19, 2017

C# Code Builder from Stored Procedure

Generic Stored Procedure to write front-end code at DAL Layer.

Usage:
EXEC SPROC_GenerateCSCodeBuilder 'Name of Stored Procedure'

Output:
It will return the front-end C# code with the usage of that Stored Procedure referenced, with sql parameters if any.

Example:

/* Use database */ 
Use YourDatabaseName

/* Calling the Proc, with the Stored Procedure name as input parameter */
EXEC SPROC_GenerateCSCodeBuilder 'TestSProcName'

/* OUTPUT */
try
   {
   SqlParameter[] sqlParams = new SqlParameter[4];
 
   sqlParams[0] = new SqlParameter("@pOldName", SqlDbType.NVarChar);
   sqlParams[0].Value = ?;
   sqlParams[0].Size=510;
   sqlParams[1] = new SqlParameter("@pNewName", SqlDbType.NVarChar);
   sqlParams[1].Value = ?;
   sqlParams[1].Size=510;
   sqlParams[2] = new SqlParameter("@pDirPath", SqlDbType.NVarChar);
   sqlParams[2].Value = ?;
   sqlParams[2].Size=2000;
   sqlParams[3] = new SqlParameter("@pExtension", SqlDbType.NVarChar);
   sqlParams[3].Value = ?;
   sqlParams[3].Size=40;
 
   SqlHelper.ExecuteNonQuery(sqlCon, CommandType.StoredProcedure,"SPROC_UpdateFileName", sqlParams);
 
   }
catch(Exception excp)
   {
   }
finally
   {
   sqlCon.Dispose();
   sqlCon.Close();
   }

Here's that stored procedure:

Create  PROCEDURE SPROC_GenerateCSCodeBuilder
(
@objName nvarchar(100)
)
AS
/*
Name:   DAL Layer Method BUilder (currently based on SQLHelper class)
Description:
  Call this stored procedue passing the name of your
  database object that you wish to insert/update
  from .NET (C#) and the code returns code to copy
  and paste into your application. This version is
  for use with "Microsoft Data Application Block".
a) Updated to include 'UniqueIdentifier' Data Type
b) Support for 'ParameterDirection.Output'
*/
SET NOCOUNT ON
DECLARE @parameterCount int
DECLARE @errMsg varchar(100)
DECLARE @parameterAt varchar(1)
DECLARE @connName varchar(100)
DECLARE @outputValues varchar(100)

--Change the following variable to the name of your connection instance
SET @connName='sqlCon'
SET @parameterAt=''
SET @outputValues=''
SELECT
  dbo.sysobjects.name AS ObjName,
  dbo.sysobjects.xtype AS ObjType,
  dbo.syscolumns.name AS ColName,
  dbo.syscolumns.colorder AS ColOrder,
  dbo.syscolumns.length AS ColLen,
  dbo.syscolumns.colstat AS ColKey,
  dbo.syscolumns.isoutparam AS ColIsOut,
  dbo.systypes.xtype
INTO #t_obj
FROM        
  dbo.syscolumns INNER JOIN
  dbo.sysobjects ON dbo.syscolumns.id = dbo.sysobjects.id INNER JOIN
  dbo.systypes ON dbo.syscolumns.xtype = dbo.systypes.xtype
WHERE    
  (dbo.sysobjects.name = @objName)
  AND
  (dbo.systypes.status <> 1)
ORDER BY
  dbo.sysobjects.name,
  dbo.syscolumns.colorder

SET @parameterCount=(SELECT count(*) FROM #t_obj)


IF(@parameterCount<1) SET @errMsg='No Parameters/Fields found for ' + @objName
IF(@errMsg is null)
BEGIN
  PRINT 'try'
  PRINT '   {'
  PRINT '   SqlParameter[] sqlParams = new SqlParameter[' + cast(@parameterCount as varchar) + '];'
  PRINT ''
 
  DECLARE @source_name nvarchar,@source_type varchar,
    @col_name nvarchar(100),@col_order int,@col_type varchar(20),
    @col_len int,@col_key int,@col_xtype int,@col_redef varchar(20), @col_isout tinyint

  DECLARE cur CURSOR FOR
  SELECT * FROM #t_obj
  OPEN cur
  -- Perform the first fetch.
  FETCH NEXT FROM cur INTO @source_name,@source_type,@col_name,@col_order,@col_len,@col_key,@col_isout,@col_xtype

  if(@source_type=N'U') SET @parameterAt='@'
  -- Check @@FETCH_STATUS to see if there are any more rows to fetch.
  WHILE @@FETCH_STATUS = 0
  BEGIN
    SET @col_redef=(SELECT CASE @col_xtype
WHEN 34 THEN 'Image'
WHEN 35 THEN 'Text'
WHEN 36 THEN 'UniqueIdentifier'
WHEN 48 THEN 'TinyInt'
WHEN 52 THEN 'SmallInt'
WHEN 56 THEN 'Int'
WHEN 58 THEN 'SmallDateTime'
WHEN 59 THEN 'Real'
WHEN 60 THEN 'Money'
WHEN 61 THEN 'DateTime'
WHEN 62 THEN 'Float'
WHEN 99 THEN 'NText'
WHEN 104 THEN 'Bit'
WHEN 106 THEN 'Decimal'
WHEN 122 THEN 'SmallMoney'
WHEN 127 THEN 'BigInt'
WHEN 165 THEN 'VarBinary'
WHEN 167 THEN 'VarChar'
WHEN 173 THEN 'Binary'
WHEN 175 THEN 'Char'
WHEN 231 THEN 'NVarChar'
WHEN 239 THEN 'NChar'
ELSE '!MISSING'
END AS C)

--Write out the parameter
PRINT '   sqlParams[' + cast(@col_order-1 as varchar)
   + '] = new SqlParameter("' + @parameterAt + @col_name
   + '", SqlDbType.' + @col_redef
   + ');'

--Write out the parameter direction it is output
IF(@col_isout=1)
BEGIN
PRINT '   sqlParams['+ cast(@col_order-1 as varchar) +'].Direction=ParameterDirection.Output;'
SET @outputValues=@outputValues+'   ?=sqlParams['+ cast(@col_order-1 as varchar) +'].Value;'
END
ELSE
BEGIN
--Write out the parameter value line
    PRINT '   sqlParams['+ cast(@col_order-1 as varchar) + '].Value = ?;'
END
--If the type is a string then output the size declaration
IF(@col_xtype=231)OR(@col_xtype=167)OR(@col_xtype=175)OR(@col_xtype=99)OR(@col_xtype=35)
BEGIN
PRINT '   sqlParams[' + cast(@col_order-1 as varchar) + '].Size=' + cast(@col_len as varchar) + ';'
END

-- This is executed as long as the previous fetch succeeds.
      FETCH NEXT FROM cur INTO @source_name,@source_type,@col_name,@col_order, @col_len,@col_key,@col_isout,@col_xtype
  END
  PRINT ''
  PRINT '   SqlHelper.ExecuteNonQuery(' + @connName + ', CommandType.StoredProcedure,"' + @objName + '", sqlParams);'
  PRINT @outputValues
  PRINT '   }'
  PRINT 'catch(Exception excp)'
  PRINT '   {'
  PRINT '   }'
  PRINT 'finally'
  PRINT '   {'
  PRINT '   ' + @connName + '.Dispose();'
  PRINT '   ' + @connName + '.Close();'
  PRINT '   }'
  CLOSE cur
  DEALLOCATE cur
 END
if(LEN(@errMsg)>0) PRINT @errMsg
DROP TABLE #t_obj
SET NOCOUNT ON