0

I want to get just schema of arbitrary sql query in SQL server.

For example-

Create Table Tabl1(Ta1bID int ,col1 varchar(10))

Create Table Tabl2(Tab1ID int ,col2 varchar(20))

SQL Query -

SELECT col1, col2  
FROM Tab1 
INNER JOIN Tab2 ON Tab1ID =  Tab2ID

Here result will have this schema-

Col1 varchar(10), Col2 varchar(20)

I want to know what will be schema of result.

PS : I have just read access on the server where I am executing this query.

Any way to do this?

2
  • Do you want to print data type of each column or just want to get schema without any data?
    – qxg
    Jun 5, 2014 at 7:35
  • Actually i have to store result in some other server.So i have to create one table there with result schema.Need to know both column names & datatypes (length also in case of nvarchar/varchar) Jun 6, 2014 at 9:24

2 Answers 2

0

The schema, you mean to say datatype right? For resulted datatype will you always know when you operate on table(s). In your case both column is varchar datatype, so it will give character datatype, that you may convert into any character datatype like varchar, nvarchar, char, ntext etc.

Basic thing is, table designing was/is done by, so that time we know why we define datatype, now when you execute query below , you always know what will come with datatype of each column.

SELECT col1, col2  
FROM Tab1 
INNER JOIN Tab2 ON Tab1ID =  Tab2ID

This though will issue when you use dynamic query, where you run time add column as per your requirement and you then execute which may or may not give error, due to mismatch of wrong datatype. like

declare @sqlstring nvarchar(max)

set @sqlstring = 'declare @t table (name varchar(50))
insert into @t values(''Minh''),(''Tinh''),(''Justin'')

Select * from @t where Name like ''%in%'''

EXEC sp_executesql @sqlstring
1
  • I have got the ans. This is what i did- SELECT * INTO #TempTable FROM (SELECT col1, col2 FROM Tab1 INNER JOIN Tab2 ON Tab1ID = Tab2ID) AS TAB. And then i read the column names and schema(datatype and length etc) for #TempTable table from tempdb.sys.columns. Sep 13, 2014 at 11:50
0

I had similar problem before, but I had to create tables (70+) of each query one by one.

  • If there is a pattern, write a tool to generate create table statement.
  • If not and it's one time job, just create them manually.
  • If it's not one time job, you might be thinking, why would store temp date in table instead of temp table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.