简体   繁体   中英

How to column schema of arbitrary query in SQL server

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM