Skip to content
No results
We use cookies to ensure that we give you the best experience on our website.

# Replace constant in SQL with SQL variables

Hard code string constant in SQL query is not a good practice, it should be replaced by SQL variable. General SQL Parser can help you to achieve this quickly.

Here is an insert statement with string constant, those string constants can be replaced by SQL variable in your program automatically.

    INSERT INTO employee(employeename,lastname) VALUES ('arun','deep')

SQL after replace string constant

    INSERT INTO employee(employeename,lastname) VALUES (@var1,@var2)

Code in C# to achieve what we mentioned above.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using gudusoft.gsqlparser;
    using gudusoft.gsqlparser.Units;

    namespace replaceconstwithvar
    {
        class replaceconstwithvar
        {
            static void Main(string[] args)
            {
                // create a sql parser instance supports ms sql server sql dialect
                TGSqlParser sqlparser = new TGSqlParser(TDbVendor.DbVMssql);

                sqlparser.SqlText.Text = @"INSERT INTO employee(employeename,lastname) VALUES ('arun','deep')";
                int iRet = sqlparser.Parse();
                int counter = 0;
                if (iRet == 0)
                {
                    foreach (TCustomSqlStatement sql in sqlparser.SqlStatements)
                    {
                        foreach (TSourceToken st in sql.SourceTokenList)
                        {
                            if
                                (
                                (st.TokenType == TTokenType.ttNumber)
                                || (st.TokenType == TTokenType.ttSQString)
                                )
                            {
                                counter++;
                                st.AsText = "@var" + counter.ToString();

                            }
                        }

                        Console.WriteLine("{0}", sql.AsText);
                    }
                }
                else
                {
                    Console.WriteLine("Syntax error found in input sql:");
                    Console.WriteLine(sqlparser.ErrorMessages);
                }

            }
        }
    }

Download this demo: C# version, Java version