Click here to Skip to main content
Licence 
First Posted 27 Sep 2004
Views 293,715
Bookmarked 224 times

C# Code Generator for Stored Procedures

By | 20 Feb 2006 | Article
This stored procedure will generate all the C# code for calling any Stored Procedure
 
Part of The SQL Zone sponsored by
See Also

Introduction

Ever got fed up with creating all the code behind parameters for your stored procedures? I have. So, I wrote this stored proc to do the code for me. (I love code that writes code). This has been written for use with "Microsoft Data Application Block" (SQLHelper.cs), however it could be hacked around to write the code without using the MDAB or even to write the code in VB. The script handles both input and output parameters, setting the size of text types, and you could even use it for direct access to a view or table.

Using the code

To implement, just copy the code into Query Analyzer and run. This will create a SPROC called "tools_CS_SPROC_Builder".

To use, just execute the SPROC passing the name of the SPROC you want the code for (see below). Note: don't include any owner prefix, e.g.: (dbo.).

EXEC tools_CS_SPROC_Builder 'mySprocsNameHere'

The message window in the Query Analyzer will write out all the code required for your class or code behind. There is a variable in "tools_CS_SPROC_Builder" called "@connName" which you can set to the name of your connection instance. By default, it's set to "conn.Connection" - just alter this for your own project's naming convention.

The code

CREATE     PROCEDURE tools_CS_SPROC_Builder
(
@objName nvarchar(100)
)
AS
/*
___________________________________________________________________
Name:  CS SPROC Builder
Version: 1
Date:  10/09/2004
Author:  Paul McKenzie
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".
  
  
*/
SET NOCOUNT ON

DECLARE @parameterCount int
DECLARE @errMsg varchar(100)
DECLARE @parameterAt varchar(1)
DECLARE @connName varchar(100)
//Change the following variable to the name of your connection instance
SET @connName='conn.Connection'
SET @parameterAt=''
  
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.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[] paramsToStore = 
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)
 
  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_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 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 '   paramsToStore[' + cast(@col_order-1 as varchar) 
    + '] = new SqlParameter("' + @parameterAt + @col_name
    + '", SqlDbType.' + @col_redef
    + ');'

   --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 '   paramsToStore[' + cast(@col_order-1 as varchar) 
     + '].Size=' + cast(@col_len as varchar) + ';'
    END
   PRINT '   paramsToStore['+ cast(@col_order-1 as varchar) 
    + '].Value =  ;'
      -- 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_xtype 
  END
  PRINT ''
  PRINT '   SqlHelper.ExecuteNonQuery(' + @connName + 
  ', CommandType.StoredProcedure,"' + @objName + '", paramsToStore);'
  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

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

Output Example

try
   {
   SqlParameter[] paramsToStore = new SqlParameter[9];
 
   paramsToStore[0] = new SqlParameter("@organisationid", SqlDbType.BigInt);
   paramsToStore[0].Value =  ;
   paramsToStore[1] = new SqlParameter("@DisplayName", SqlDbType.NVarChar);
   paramsToStore[1].Size=100;
   paramsToStore[1].Value =  ;
   paramsToStore[2] = new SqlParameter("@DefaultCurrencyFID", SqlDbType.Int);
   paramsToStore[2].Value =  ;
   paramsToStore[3] = new SqlParameter("@TaxCode", SqlDbType.NVarChar);
   paramsToStore[3].Size=60;
   paramsToStore[3].Value =  ;
   paramsToStore[4] = new SqlParameter("@UserFID", SqlDbType.BigInt);
   paramsToStore[4].Value =  ;
   paramsToStore[5] = new SqlParameter("@IsClient", SqlDbType.Bit);
   paramsToStore[5].Value =  ;
   paramsToStore[6] = new SqlParameter("@IsContractor", SqlDbType.Bit);
   paramsToStore[6].Value =  ;
   paramsToStore[7] = new SqlParameter("@IsSupplier", SqlDbType.Bit);
   paramsToStore[7].Value =  ;
   paramsToStore[8] = new SqlParameter("@IsDesigner", SqlDbType.Bit);
   paramsToStore[8].Value =  ;
 
   SqlHelper.ExecuteNonQuery(conn.Connection, 
CommandType.StoredProcedure,"usp_Insert_Organisation", paramsToStore);
   }
catch(Exception excp)
   {
   }
finally
   {
   conn.Connection.Dispose();
   conn.Connection.Close();
   }

All you then have to do is copy-paste and fill in the values you want to pass and catch any exceptions... (Yes you do have to write some code!).

Points of Interest

In order for me to work out the @col_xtype variable from sysobjects, I ran lots of tests on a table I created with every type variation in both directions. It certainly works fine for all the usual data types, but I haven't had a chance to test all types within .NET, so if you find a bug, let me know. Enjoy!

History

  • Feb 20, 2006 - updated the script to version 1.1 which includeds two additions:
    1. UniqueIdentifier data type support.
    2. Support for ParameterDirection.Output.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

PaulMcKenzie

Software Developer (Senior)

United Kingdom United Kingdom

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralRe: My generator - http://www.codeauthor.org PinmemberSupermanDT9:25 1 Aug '07  
GeneralRe: My generator - http://www.codeauthor.org Pinsussalpha9:12 7 Dec '07  
GeneralRe: My generator - http://www.codeauthor.org PinmemberHamed Mosavi4:07 3 Oct '08  
Questionoutput variables Pinmemberchacimulch3:51 10 Nov '06  
GeneralCool, but not quite what I'm looking for PinmemberJudah Himango4:59 1 Mar '06  
NewsI GOT WHAT YOUR LOOKING FOR! how bad do u want it? lol. [modified] Pinmembermeaningoflights0:05 5 Jun '07  
GeneralCONVERTED TO VB.NET & Enterprise Library 2.0 Data Access Application Block PinmemberjAY wASSER10:35 28 Feb '06  

CREATE                  PROCEDURE tools_CS_SPROC_Builder_2005
(
@objName nvarchar(100),
@Executetype nvarchar(100) -- ExecuteNonQuery -or- ExecuteReader -or- ExecuteScalar
)
AS
/*
___________________________________________________________________
Name:             CS SPROC Builder
Version:      1
Date:           10/09/2004
Author:        Paul McKenzie
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".
  
Version:      1.1
Date:          17/02/2006
Author:          Paul McKenzie
Description:     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='ConfigurationSettings.AppSettings("connectionString")'
SET @parameterAt=''
SET @outputValues=''
SELECT
     dbo.sysobjects.name AS ObjName,
     dbo.sysobjects.xtype AS ObjType,
     REPLACE(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
 
          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

         
 
         
          IF @ExecuteType = 'ExecuteNonQuery'
          BEGIN
               PRINT 'SUB '+@objName+'( _'
          END
          IF @ExecuteType = 'ExecuteReader'
          BEGIN
               PRINT 'FUNCTION '+@objName+'( _'
          END
          IF @ExecuteType = 'ExecuteScalar'
          BEGIN
               PRINT 'FUNCTION '+@objName+'( _'
          END
 

          declare @parameterOut nvarchar(1000)
 
          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 'Binary'
                         WHEN 35 THEN 'String'
                         WHEN 36 THEN 'Guid'
                         WHEN 48 THEN 'Byte'
                         WHEN 52 THEN 'Int16'
                         WHEN 56 THEN 'Int32'
                         WHEN 58 THEN 'DateTime'
                         WHEN 59 THEN 'Single'
                         WHEN 60 THEN 'Currency'
                         WHEN 61 THEN 'DateTime'
                         WHEN 62 THEN 'Double'
                         WHEN 99 THEN 'String'
                         WHEN 104 THEN 'Boolean'
                         WHEN 106 THEN 'Decimal'
                         WHEN 122 THEN 'Currency'
                         WHEN 127 THEN 'Int64'
                         WHEN 165 THEN 'Binary'
                         WHEN 167 THEN 'String'
                         WHEN 173 THEN 'Binary'
                         WHEN 175 THEN 'String'
                         WHEN 231 THEN 'String'
                         WHEN 239 THEN 'String'
                         ELSE '!MISSING'
                         END AS C)
 
                    --capture parameter
                    select @parameterOut = '   ByVal ' + @col_name+ ' AS '+@col_redef
 
                    -- 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
 
                    IF @@FETCH_STATUS<>0
                    BEGIN
                         PRINT @parameterOut + ' _'
                    END
                    IF @@FETCH_STATUS=0
                    BEGIN
                         PRINT @parameterOut+',   _'
                    END
                  END
          CLOSE cur
          DEALLOCATE cur
 
          IF @ExecuteType = 'ExecuteNonQuery'
          BEGIN
               PRINT ')'
          END
          IF @ExecuteType = 'ExecuteReader'
          BEGIN
               PRINT ') AS SQLDATAREADER'
          END
          IF @ExecuteType = 'ExecuteScalar'
          BEGIN
               PRINT ') AS ?'
          END
 

 
          PRINT ''
          PRINT '   Dim db As Database = DatabaseFactory.CreateDatabase() '
          PRINT '   Dim sqlCommand As String = "'+@objName+'" '
          PRINT '   Dim dbCommand As DbCommand = db.GetStoredProcCommand(sqlCommand) '
          PRINT ''
  
            
             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 'Binary'
                         WHEN 35 THEN 'String'
                         WHEN 36 THEN 'Guid'
                         WHEN 48 THEN 'Byte'
                         WHEN 52 THEN 'Int16'
                         WHEN 56 THEN 'Int32'
                         WHEN 58 THEN 'DateTime'
                         WHEN 59 THEN 'Single'
                         WHEN 60 THEN 'Currency'
                         WHEN 61 THEN 'DateTime'
                         WHEN 62 THEN 'Double'
                         WHEN 99 THEN 'String'
                         WHEN 104 THEN 'Boolean'
                         WHEN 106 THEN 'Decimal'
                         WHEN 122 THEN 'Currency'
                         WHEN 127 THEN 'Int64'
                         WHEN 165 THEN 'Binary'
                         WHEN 167 THEN 'String'
                         WHEN 173 THEN 'Binary'
                         WHEN 175 THEN 'String'
                         WHEN 231 THEN 'String'
                         WHEN 239 THEN 'String'
                         ELSE '!MISSING'
                         END AS C)
 
                    --Write out the parameter
                    IF(@col_isout<>1)
                    BEGIN
                         PRINT '   db.AddInParameter(dbCommand, "' + @col_name+ '", DbType.'+@col_redef+', ' + @col_name+ ')'
                    END
                    --Write out the parameter direction it is output
                    IF(@col_isout=1)
                    BEGIN
                         PRINT '   db.AddOutParameter(dbCommand, "' + @col_name+ '", DbType.'+@col_redef+', ' + @col_name+ ')'
                    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 ''
     IF @ExecuteType = 'ExecuteNonQuery'
     BEGIN
          PRINT '   db.ExecuteNonQuery(dbCommand)'
          PRINT 'END SUB'
     END
     IF @ExecuteType = 'ExecuteReader'
     BEGIN
          PRINT '   Return db.ExecuteReader(dbCommand) '
          PRINT 'END FUNCTION'
     END
     IF @ExecuteType = 'ExecuteScalar'
     BEGIN
          PRINT '   Return db.ExecuteScalar(dbCommand) '
          PRINT 'END FUNCTION'
     END
 
        CLOSE cur
     DEALLOCATE cur
END
if(LEN(@errMsg)>0) PRINT @errMsg
DROP TABLE #t_obj
SET NOCOUNT ON
 
GO

GeneralMS DAAB Jan 2006 Version Pinmemberzac everett22:34 5 Feb '06  
GeneralCodes for SQLTypes Pinmembersolusoft0:46 22 Dec '05  
QuestionOracle Procedure? Pinmemberjhtang9:18 16 Dec '05  
GeneralDAL Generator Pinmemberm2xdam20:53 15 Nov '05  
GeneralRe: DAL Generator PinmemberOwen Gunter0:10 6 Jan '06  
Generalmissing UniqueIdentifier Pinmembermliss10:51 4 Nov '05  
GeneralYou are AWESOME! Pinmemberdrkwtkns3:31 14 Apr '05  
Generalgreat stuff Pinmemberswamp610:39 31 Jan '05  
GeneralNice... PinmembertheJazzyBrain4:04 13 Nov '04  
GeneralNice code PinmemberPhan Dung18:14 27 Oct '04  
GeneralSqlHelperParameterCache PinmemberHe Who Codes12:56 7 Oct '04  
GeneralMDAB params overload PinmemberSteveBacon1:50 7 Oct '04  
GeneralGreat idea PinmemberMark Morgen6:39 6 Oct '04  
GeneralRe: Great idea PinmemberMcCodeJunky7:49 7 Oct '04  
GeneralUse DeriveParameters() instead PinmemberJeff Firestone6:23 6 Oct '04  
GeneralRe: Use DeriveParameters() instead PinmemberMcCodeJunky7:41 7 Oct '04  
GeneralRe: Use DeriveParameters() instead PinmemberJeff Firestone8:27 7 Oct '04  
Generalnice approach PinmemberAshley van Gerven18:17 30 Sep '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 20 Feb 2006
Article Copyright 2004 by PaulMcKenzie
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid