Auto Query Generator In MSSQL Server

MSSQL Server 

If you’re a developer, irrespective of the platform, you  have to work with databases. Creating SQL statements for tables is quite often a monotonous job and it gets hectic especially when dealing with gigantic tables that have hundreds of columns. Writing SQL statements manually every time becomes a tiresome process.

Before explaining the script, I want to share the reason to write this script and how it is helping my peers. We have code standard on the database side. Below points are standards.
  • Need to maintain a separate stored procedure to every table
  • Don’t use * in the query instead specify the column
  • Use the correct data type and size of a column
  • Every parameter should be nullable in a stored procedure.

I am developing an application which is related to machines using .NET and SQL Server. The database design consists of some master tables and transactional tables. All the transactional table has more than 30 columns.

To meet my code standards, I need to mention all columns with correct data type and size in stored procedure parameters like below,

  1. CREATEproc [dbo].[USP_PCNitemCreation] ( @Id int, @machineName varchar(50)=NULL, @furnacename varchar(50)=NULL, @minValue int=NULL, @maxValue int=NULL, @createdDate datetime=nullvarchar(100)=NULL )  

All the queries should specify the column instead of using the start(*).

  1. select machineName,furnacename from trn_furnace where Id=@Id  

It consumes more time and is a boring task. So, I plan to write the script to is cut down on the time it takes and boring repeated work. We cannot automate the logic, but we can automate the repeated task.

Then I write the below script which really cuts down on all of our above pain points.

Auto Query Generator Stored Procedure for MSSQL Server,

  1. CREATEproc [dbo].[USP_QuerycreationSupport] ( @table_Name varchar(100)=NULL ) AS   
  2. BEGINDECLARE @InserCols   NVARCHAR(max)DECLARE @Inserparam  NVARCHAR(max)DECLARE @Insertquery NVARCHAR(max)DECLARE @Selectquery NVARCHAR(max)DECLARE @Update      NVARCHAR(max)DECLARE @DeleteQuery NVARCHAR(max)  
  3.   -- sp paramSELECT '@'+c.NAME+Space(1)+Casecast(t.Nameasnvarchar(40))WHEN'nvarchar'THEN   
  4.   t.NAME    +'('+cast(c.max_length asnvarchar(30))+')'   
  5. WHEN'varchar'THEN   
  6.   t.NAME+'('+cast(c.max_length asnvarchar(30))+')'   
  7. WHEN'char'THEN   
  8.   t.NAME+'('+cast(c.max_length asnvarchar(30))+')'   
  9. WHEN'decimal'THEN   
  10.   t.NAME        +'(18,2)'   
  11.   ELSE t.nameend+'=null,'AS colss FROM sys.columns c innerjoin sys.types t ON c.user_type_id = t.user_type_id leftouterjoin sys.index_columns ic ON ic.object_id= c.object_idand ic.column_id = c.column_id leftouterjoin sys.indexes i ON ic.object_id= i.object_idand ic.index_id = i.index_id WHERE c.object_id=object_id(@table_Name)SELECT'Insert query'SET @InserCols=(selectdistinct   
  12.   (   
  13.          select sc.NAME+','   
  14.          FROM   sys.tables st innerjoinsys.columns sc   
  15.          ON st.object_id= sc.object_id   
  16.          WHERE  st.NAME= @table_Name forxmlpath(''),   
  17.                 type).value('.','NVARCHAR(MAX)'))   
  18.   -- Return the result of the functionSELECT @InserCols=LEFT(@InserCols,Len(@InserCols)-1)   
  19.   --select @InserColsSET @Inserparam=(selectdistinct   
  20.   (   
  21.          select'@'+sc.NAME+','   
  22.          FROM   sys.tables st innerjoinsys.columns sc   
  23.          ON st.object_id= sc.object_id   
  24.          WHERE  st.NAME= @table_Name forxmlpath(''),   
  25.                 type).value('.','NVARCHAR(MAX)'))   
  26.   -- Return the result of the functionSELECT @Inserparam=LEFT(@Inserparam,Len(@Inserparam)-1)   
  27.   --select @InserparamSET @Insertquery='insert into '+@table_Name+'('+@InserCols+')'+'values'+'('+@Inserparam+')'SELECT @InsertquerySELECT'Update Query'SET @Update=(selectdistinct   
  28.   (   
  29.          select sc.NAME+'=@'+sc.NAME+','   
  30.          FROM   sys.tables st innerjoinsys.columns sc   
  31.          ON st.object_id= sc.object_id   
  32.          WHERE  st.NAME= @table_Name forxmlpath(''),   
  33.                 type).value('.','NVARCHAR(MAX)'))   
  34.   -- Return the result of the functionSELECT @Update=LEFT(@Update,Len(@Update)-1)   
  35.   --select @UpdateSET @Update='UPdate '+@table_Name+' set '+@UpdateSELECT @Update   
  36.   -- For select QuerySELECT'Select Query'SET @Selectquery='select '+@InserCols +' from '+ @table_NameSELECT @Selectquery  
  37.   -- For Delete QuerySELECT'Delete Query'SET @DeleteQuery='delete from '+ @table_NameSELECT @DeleteQuery  
  38. end  

How to use this script,

  • Step 1 - Create the stored procedure using the above code or attached code.
  • Step 2 - Execute the stored procedure and pass your table name as a parameter.

  1. Exec USP_QuerycreationSupport@table_Name='mstCustomer'  

Should not pass the database object in the table name

  1. Exec USP_QuerycreationSupport@table_Name='[dbo].[mstCustomer]'  

Once you execute the Stored Procedure as mentioned above, you get all the SQL statements as shown here. You could easily use the generated SQL statements elsewhere. You get all basic SQL statements like Select, Insert, Update & Delete.

MSSQL Server 

How could this Auto Query Generator benefit you?

  • Minimizes your time in Query Creation
  • Eliminates human errors in datatype mismatches, size etc.
  • Irrespective of table size, you get all basic SQL instantly
  • Especially comes in handy while dealing with a table that has hundreds of columns

I hope this article helps you. Please comment below, if you have any query on this article.