Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 48505
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T16:17:26+00:00 2026-05-10T16:17:26+00:00

I want to ask how other programmers are producing Dynamic SQL strings for execution

  • 0

I want to ask how other programmers are producing Dynamic SQL strings for execution as the CommandText of a SQLCommand object.

I am producing parameterized queries containing user-generated WHERE clauses and SELECT fields. Sometimes the queries are complex and I need a lot of control over how the different parts are built.

Currently, I am using many loops and switch statements to produce the necessary SQL code fragments and to create the SQL parameters objects needed. This method is difficult to follow and it makes maintenance a real chore.

Is there a cleaner, more stable way of doing this?

Any Suggestions?

EDIT: To add detail to my previous post:

  1. I cannot really template my query due to the requirements. It just changes too much.
  2. I have to allow for aggregate functions, like Count(). This has consequences for the Group By/Having clause. It also causes nested SELECT statements. This, in turn, effects the column name used by
  3. Some Contact data is stored in an XML column. Users can query this data AS WELL AS and the other relational columns together. Consequences are that xmlcolumns cannot appear in Group By clauses[sql syntax].
  4. I am using an efficient paging technique that uses Row_Number() SQL Function. Consequences are that I have to use a Temp table and then get the @@rowcount, before selecting my subset, to avoid a second query.

I will show some code (the horror!) so that you guys have an idea of what I’m dealing with.

sqlCmd.CommandText = 'DECLARE @t Table(ContactId int, ROWRANK int' + declare       + ')INSERT INTO @t(ContactId, ROWRANK' + insertFields + ')'//Insert as few cols a possible       + 'Select ContactID, ROW_NUMBER() OVER (ORDER BY ' + sortExpression + ' '       + sortDirection + ') as ROWRANK' // generates a rowrank for each row       + outerFields       + ' FROM ( SELECT c.id AS ContactID'       + coreFields       + from         // sometimes different tables are required        + where + ') T ' // user input goes here.       + groupBy+ ' '       + havingClause //can be empty       + ';'       + 'select @@rowcount as rCount;' // return 2 recordsets, avoids second query       + ' SELECT ' + fields + ',field1,field2' // join onto the other cols n the table       +' FROM @t t INNER JOIN contacts c on t.ContactID = c.id'        +' WHERE ROWRANK BETWEEN ' + ((pageIndex * pageSize) + 1) + ' AND '        + ( (pageIndex + 1) * pageSize); // here I select the pages I want 

In this example, I am querying XML data. For purely relational data, the query is much more simple. Each of the section variables are StringBuilders. Where clauses are built like so:

// Add Parameter to SQL Command AddParamToSQLCmd(sqlCmd, '@p' + z.ToString(), SqlDbType.VarChar, 50, ParameterDirection.Input, qc.FieldValue); // Create SQL code Fragment where.AppendFormat(' {0} {1} {2} @p{3}', qc.BooleanOperator, qc.FieldName, qc.ComparisonOperator, z); 
  • 1 1 Answer
  • 3 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T16:17:26+00:00Added an answer on May 10, 2026 at 4:17 pm

    I had the need to do this on one of my recent projects. Here is the scheme that I am using for generating the SQL:

    • Each component of the query is represented by an Object (which in my case is a Linq-to-Sql entity that maps to a table in the DB). So I have the following classes: Query, SelectColumn, Join, WhereCondition, Sort, GroupBy. Each of these classes contains all details relating to that component of the query.
    • The last five classes are all related to a Query object. So the Query object itself has collections of each class.
    • Each class has a method that can generate the SQL for the part of the query that it represents. So creating the overall query ends up calling Query.GenerateQuery() which in turn enumerates through all of the sub-collections and calls their respective GenerateQuery() methods

    It is still a bit complicated, but in the end you know where the SQL generation for each individual part of the query originates (and I don’t think that there are any big switch statements). And don’t forget to use StringBuilder.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 199k
  • Answers 199k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I took a look at your code and this might… May 12, 2026 at 7:50 pm
  • Editorial Team
    Editorial Team added an answer Try try { elem = document.getElementById('asd'); elem.style.background = '-moz-linear-gradient(top, rgba(138,… May 12, 2026 at 7:50 pm
  • Editorial Team
    Editorial Team added an answer It should work the other way around: all = [x… May 12, 2026 at 7:50 pm

Related Questions

Let's face it. The Singleton Pattern is highly controversial topic with hordes programmers on
I'm just now learning to programming at age 17. It's hard for me to
I'm writing a piece of software over on github. It's basically a tray icon
I noticed that the fieldset tag renders a rounded corner border on IE (it

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.