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 6716141
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T08:41:52+00:00 2026-05-26T08:41:52+00:00

The problem is that: In SQL Server,I have a SELECT statement that might take

  • 0

The problem is that:
In SQL Server,I have a SELECT statement that might take any form like

SELECT ID,Name
FROM Table1;

Or

SELECT ID,Name
FROM Table1
WHERE ID IN(
SELECT ID
FROM Table2
WHERE City = 'C1'
)

or

SELECT *
FROM
(
  SELECT ID,Name
  FROM Tablex
  INTERSECT
  SELECT ID,Name
  FROM Tablex
) AS T

or whatever sql statement that might be very complex, and I need to generate the CREATE TABLE statement that creates a table with a structure that can hold the data of the result set returned by the SELECT statement.

The code can be C# or T-SQL.

EDIT:

The SELECT statement is a parameter passed to my application.The SELECT statement usually returns millions of records that will be transferred from a server to another so I need the CREATE TABLE script to be executed on the destination server to which the data will be transferred.

  • 1 1 Answer
  • 0 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. Editorial Team
    Editorial Team
    2026-05-26T08:41:52+00:00Added an answer on May 26, 2026 at 8:41 am

    Here is my try inspired from the comments on my question, and many thanks to everybody:

    class Program
        {
            static void Main(string[] args)
            {
                using (SqlConnection con = new SqlConnection("server=myserver;database=mydb;user id=sa;password=mypassword;"))
                {
    
                    Console.WriteLine(GetCreateTableFromSqlCode(@"
    SELECT ID,Eid,Keyword AS Keywords,KeywordType AS Sources,Year
    FROM Eid_Keywords 
    WHERE Eid IN(SELECT Eid FROM ReviewersPublications)","Keywords",con));                
    
                }
            }
    
            public static string GetCreateTableFromSqlCode(string sqlSelect,string tableName, SqlConnection con)
            {            
                SqlCommand cmd = new SqlCommand(string.Format("SET FMTONLY ON;\r\n{0}\r\nSET FMTONLY OFF;",sqlSelect), con);
                try
                {
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    DataTable dt = reader.GetSchemaTable();
                    reader.Close();
                    return GetCreateTableScript(dt, tableName);
    
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();
                }
    
            }
    
            private static string GetCreateTableScript(DataTable dt,string tableName)
            {
                string snip = string.Empty;
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("CREATE TABLE {0}\r\n(\r\n",tableName);
                for (int i = 0; i < dt.Rows.Count;i++)
                {
                    DataRow dr = dt.Rows[i];
                    snip = GetColumnSql(dr);
                    sql.AppendFormat((i < dt.Rows.Count - 1) ? snip : snip.TrimEnd(',','\r','\n'));
                }
                sql.AppendFormat("\r\n)");
                return sql.ToString();
            }
    
    
            private static string GetColumnSql(DataRow dr)
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("\t[{0}] {1}{2} {3} {4},\r\n",
                    dr["ColumnName"].ToString(),
                    dr["DataTypeName"].ToString(),
                    (HasSize(dr["DataTypeName"].ToString())) ? "(" + dr["ColumnSize"].ToString() + ")" : (HasPrecisionAndScale(dr["DataTypeName"].ToString())) ? "(" + dr["NumericPrecision"].ToString() + "," + dr["NumericScale"].ToString() + ")" : "",
                    (dr["IsIdentity"].ToString() == "true") ? "IDENTITY" : "",
                    (dr["AllowDBNull"].ToString() == "true") ? "NULL" : "NOT NULL");
                return sql.ToString();
            }
    
            private static bool HasSize(string dataType)
            {            
                Dictionary<string, bool> dataTypes = new Dictionary<string, bool>();
                dataTypes.Add("bigint", false);
                dataTypes.Add("binary", true);
                dataTypes.Add("bit", false);
                dataTypes.Add("char", true);
                dataTypes.Add("date", false);
                dataTypes.Add("datetime", false);
                dataTypes.Add("datetime2", false);
                dataTypes.Add("datetimeoffset", false);
                dataTypes.Add("decimal", false);
                dataTypes.Add("float", false);
                dataTypes.Add("geography", false);
                dataTypes.Add("geometry", false);
                dataTypes.Add("hierarchyid", false);
                dataTypes.Add("image", true);
                dataTypes.Add("int", false);
                dataTypes.Add("money", false);
                dataTypes.Add("nchar", true);
                dataTypes.Add("ntext", true);
                dataTypes.Add("numeric", false);
                dataTypes.Add("nvarchar", true);
                dataTypes.Add("real", false);
                dataTypes.Add("smalldatetime", false);
                dataTypes.Add("smallint", false);
                dataTypes.Add("smallmoney", false);
                dataTypes.Add("sql_variant", false);
                dataTypes.Add("sysname", false);
                dataTypes.Add("text", true);
                dataTypes.Add("time", false);
                dataTypes.Add("timestamp", false);
                dataTypes.Add("tinyint", false);
                dataTypes.Add("uniqueidentifier", false);
                dataTypes.Add("varbinary", true);
                dataTypes.Add("varchar", true);
                dataTypes.Add("xml", false);
                if (dataTypes.ContainsKey(dataType))
                    return dataTypes[dataType];
                return false;
            }
    
            private static bool HasPrecisionAndScale(string dataType)
            {
                Dictionary<string, bool> dataTypes = new Dictionary<string, bool>();
                dataTypes.Add("bigint", false);
                dataTypes.Add("binary", false);
                dataTypes.Add("bit", false);
                dataTypes.Add("char", false);
                dataTypes.Add("date", false);
                dataTypes.Add("datetime", false);
                dataTypes.Add("datetime2", false);
                dataTypes.Add("datetimeoffset", false);
                dataTypes.Add("decimal", true);
                dataTypes.Add("float", true);
                dataTypes.Add("geography", false);
                dataTypes.Add("geometry", false);
                dataTypes.Add("hierarchyid", false);
                dataTypes.Add("image", false);
                dataTypes.Add("int", false);
                dataTypes.Add("money", false);
                dataTypes.Add("nchar", false);
                dataTypes.Add("ntext", false);
                dataTypes.Add("numeric", false);
                dataTypes.Add("nvarchar", false);
                dataTypes.Add("real", true);
                dataTypes.Add("smalldatetime", false);
                dataTypes.Add("smallint", false);
                dataTypes.Add("smallmoney", false);
                dataTypes.Add("sql_variant", false);
                dataTypes.Add("sysname", false);
                dataTypes.Add("text", false);
                dataTypes.Add("time", false);
                dataTypes.Add("timestamp", false);
                dataTypes.Add("tinyint", false);
                dataTypes.Add("uniqueidentifier", false);
                dataTypes.Add("varbinary", false);
                dataTypes.Add("varchar", false);
                dataTypes.Add("xml", false);
                if (dataTypes.ContainsKey(dataType))
                    return dataTypes[dataType];
                return false;
            }
    
    
    
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: SQL Server Database query help Hi, I have a problem that I
I have a problem that I would like have solved via a SQL query.
I have a perplexing SQL select statement (ugly) that I'm trying to write in
I have an interesting SQL problem that I need help with. Here is the
I like using LINQ to SQL. The only problem is that I don't like
I have my project in .NET that uses a database in SQL Server. I'm
I have a query in SQL Server that I am trying to convert to
I have a SQL Server table that contains postal addresses. In preparation for mailing,
I have a report that I would like to base on a single SQL
Possible Duplicate: Howto build a SQL statement with using IDs that might not be

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.