Auto Generate SQL Variable Syntax for Table Column Names

By:   |   Updated: 2024-09-16   |   Comments (2)   |   Related: > TSQL


Problem

I work with SQL tables with many programming languages. Often, I need to code variables related to the table column names. Is there any easier way that doesn't involve excessive typing?

Solution

As a Developer, automation is the most efficient way to save time when dealing with repetitive tasks. To illustrate, the code below produces a table about car details:

CREATE TABLE [dbo].[Automobile](
   [EventId] [int] IDENTITY(1,1) NOT NULL,
   [AutomobileId] [nvarchar](50) NULL,
   [Day] [date] NOT NULL,
   [Place] [nvarchar](50) NULL,
   [Amount] [money] NULL,
   [Price] [money] NULL,
   [Odometer] [int] NULL,
   [Comments] [nvarchar](50) NULL,
   [Mileage] [int] NULL,
   [Consumption] [money] NULL,
   [FuelEfficiency]  AS ([Mileage]/[Consumption]),
   [ModifiedDate] [datetime] NULL,
   [ModifiedBy] [nvarchar](50) NULL,
 CONSTRAINT [PK_Automobile] PRIMARY KEY CLUSTERED 
(
   [EventId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

In the Project Explorer of SQL Server Management Studio, right-click on the table name. Choose Script Table as > UPDATE To/ INSERT To > New Query Editor Window. The following will appear:

Insert and Update queries template

Next, we need to fill out the values or set portions of these queries. There is a way to speed up this process using the [INFORMATION_SCHEMA].[COLUMNS] table.

Creation of the Store Procedure

-- ==================================================
-- Author:      Sebastião Pereira - MSSQLTips
-- Create date: 20240723
-- Description: Columns Tool based on Template
-- ==================================================
CREATE PROCEDURE [dbo].[uspTableToModel] 
         (@Schema varchar(50)
         ,@Table varchar(50)
         ,@Template nvarchar(500)
         ,@ShowAsList bit
         ,@ConvertNet bit)
WITH EXECUTE AS CALLER
AS
BEGIN
   SET NOCOUNT ON;
   BEGIN TRY
 
      /* Convention:
         Symbol Column
         {cn} [COLUMN_NAME] 
         {dt} [DATA_TYPE]
      */
 
      IF @ShowAsList = 0 
         SELECT    REPLACE(REPLACE(@Template
                    ,'{cn}',[COLUMN_NAME])
                     ,'{dt}',[dbo].[ufnReturnSqlDataType] ([DATA_TYPE],[CHARACTER_MAXIMUM_LENGTH],@ConvertNet)) AS [Result]
            FROM  [INFORMATION_SCHEMA].[COLUMNS]
            WHERE  [TABLE_SCHEMA] = @Schema AND
                [TABLE_NAME] = @Table;
      ELSE
         SELECT     STRING_AGG(REPLACE(REPLACE(@Template
                     ,'{cn}',[COLUMN_NAME])
                     ,'{dt}',[dbo].[ufnReturnSqlDataType] ([DATA_TYPE],[CHARACTER_MAXIMUM_LENGTH],@ConvertNet)), ',') 
                  WITHIN GROUP (ORDER BY [ORDINAL_POSITION]) AS [Result]
            FROM  [INFORMATION_SCHEMA].[COLUMNS]
            WHERE  [TABLE_SCHEMA] = @Schema AND
                [TABLE_NAME] = @Table;
 
   END TRY
   BEGIN CATCH
      IF @@TRANCOUNT > 0
         BEGIN
            ROLLBACK TRANSACTION;
         END
         
      -- Print error information. 
      PRINT  'Error: ' + CONVERT(varchar(50), ERROR_NUMBER()) +
         ', Severity: ' + CONVERT(varchar(5), ERROR_SEVERITY()) +
         ', State: ' + CONVERT(varchar(5), ERROR_STATE()) + 
         ', Procedure: ' + ISNULL(ERROR_PROCEDURE(), '-') + 
         ', Line: ' + CONVERT(varchar(5), ERROR_LINE()) + 
         ', User: ' + CONVERT(varchar(5), GETDATE());
      PRINT ERROR_MESSAGE();
   END CATCH; 
END
GO

Creation of the Function

-- ==================================================
-- Author:      Sebastião Pereira - MSSQLTips
-- Create date: 20240723
-- Description: Return SQL Data type
-- ==================================================
CREATE FUNCTION [dbo].[ufnReturnSqlDataType] 
            (@DataType nvarchar(50)
            ,@MaxLength nvarchar(50)
            ,@ConvertToDotNet bit)
RETURNS nvarchar(MAX)
WITH EXECUTE AS CALLER
AS
BEGIN
   DECLARE @Result nvarchar(MAX);
 
   IF @ConvertToDotNet = 1
      BEGIN
         SET @Result =
            CASE 
               WHEN @DataType IN ('bigint') THEN 'long'
               WHEN @DataType IN ('int') THEN 'int'
               WHEN @DataType IN ('smallint') THEN 'short'
               WHEN @DataType IN ('tinyint') THEN 'byte'
               WHEN @DataType IN ('bit') THEN 'boolean'
               WHEN @DataType IN ('decimal','numeric','money','smallmoney') THEN 'decimal'
               WHEN @DataType IN ('float') THEN 'double'
               WHEN @DataType IN ('real') THEN 'single'
               WHEN @DataType IN ('char','nchar','varchar','nvarchar','text','ntext') THEN 'string'
               WHEN @DataType IN ('date','datetime','datetime2','smalldatetime') THEN 'DateTime'
               WHEN @DataType IN ('time') THEN 'TimeSpan'
               WHEN @DataType IN ('datetimeoffset') THEN 'DateTimeOffset'
               WHEN @DataType IN ('binary','varbinary','image','timestamp','rowversion') THEN 'byte[]'
               WHEN @DataType IN ('uniqueidentifier') THEN 'guid'
               WHEN @DataType IN ('xml') THEN 'XmlDocument'
               WHEN @DataType IN ('sql_variant') THEN 'Object'
            END;
      END
   ELSE
      SET @Result = CONCAT(@DataType,'(' + CONVERT(varchar(10),@MaxLength) + ')');
 
   RETURN @Result;
END
GO

Filling Out Data

Our stored procedure has five variables:

  1. @Schema: the name of the schema of the table that we want to query.
  2. @Table: the table name.
  3. @Template: what we want to retrieve using as a convention {cn} for Column name and {dt} for Data type.
  4. @ShowAsList: if false, will return the data in rows, and if true, will return as a string.
  5. @ConvertNet: if false, will return SQL data types, and if true, will return .NET data types.

Templates examples

For the Automobile table running with these templates will generate the respective results for the column PLACE:

Template Result with @ConvertNet = False Result with @ConvertNet = True
Column {cn} has a data type {dt} Column Place has a data type nvarchar(50) Column Place has a data type string
{dt} {cn} nvarchar(50) Place string Place
public {dt} {cn} { get; set;} Public nvarchar(50) Place { get; set;} Public string Place { get; set;}

Convert to Net example

convert to net

Insert Case

To insert the values clause, we need to pass them with variables. The trick is to create a template like N',@{cn}', execute the store procedure, select the result, and copy and paste the VALUES clause of the query. Remember to remove the comma from the first element and refine the formatting of your code.

Insert query - cut and paste

Update Case

Now, to insert the set elements, we will create the template N',[{cn}] = @{cn}', execute the stored procedure, select the result, and copy and paste the SET clause of the query. Remember to remove the comma from the first element and refine the formatting of your code.

Update query - Cut and Paste

Other Useful Cases

Developers often encounter situations where they need to create repetitive statements related to SQL table columns. Here are a few examples.

Note: This is only a sample of example situations. They are too numerous to include in this article.

Creating a Class in C#

C# Class elements

Creating a Class in VB

VB Net class elements

Initializing Variables in VUE

VUE variables initialization

List of All Columns with their Data Type and Column Name Separated by Comma

Table data types and column names

List of Column Names as Variables

List of column names as variables

List of All Columns with their Data Type in .NET and Column Name

List of data types in .Net and columns

Statement in SQL to Check if the Column is Different than its Variable, Then Change It; Otherwise Set as Null

A case when statement


List of Columns Names Surrounded By Quotes and Double Quotes

A specific statement for columns

The result value of this stored procedure can be used in any programming task related to SQL table columns. Simply copy and paste the output into your code, then fix the formatting and make any necessary adjustments.

Next Steps
  • Pay attention to details like removing the comma in the first element, aligning the items, and using only the values of the needed columns.
  • If you need to improve the stored procedure, you can use the column [IS_NULLABLE] to check when it is necessary to include the term REQUIRED in the result set.


sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Sebastiao Pereira Sebastiao Pereira has over 38 years of healthcare experience, including software development expertise with databases.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2024-09-16

Comments For This Article




Monday, September 16, 2024 - 10:23:43 AM - Sebastião Back To Top (92501)
If I understand your comment correctly, I need to better explain how the data type conversion works.

When the variable @ConvertNet is set to True this only changes the return type to .NET. For example, changing nvarchar(..) to string, money to decimal, and so on. But in the template must have the {dt} portion specified for this to happen.

Please see this image as a point of reference - https://www.mssqltips.com/tipImages2/TipID_8084_TipComment_20240916.png.

Monday, September 16, 2024 - 1:58:14 AM - Dimitris Back To Top (92498)
hi,
very usefull code
but IMHO this variable @ConvertNet doesn't work
allthough I set value 1 doesn't return column's data type
thanks in advance














get free sql tips
agree to terms