-2

I am trying to figure out a way to name my columns in a newly declared table by fetching the name from another source like another string or value in another table.

What I want to know is something like this is possible or not?

In below code I have declared a string and entered a value.

I want this value to be the column name in my table below. Can anyone help me fix this?

declare @string3 varchar(max);
set @string3 = 'LIST_TYPE';
select @string3;

DECLARE @TABP TABLE 
(

id int,
@string3 varchar(max)

)
Thom A
  • 88,727
  • 11
  • 45
  • 75
Tom
  • 15
  • 1
  • 8
  • you would need to use dynamic SQL, however with a temp table that poses additional complications, explain what you are trying to do and why you need this. – Stu Feb 14 '22 at 09:25
  • 1
    It can be done using dynamic SQL, however you should first ask yourself if it should be done. Dynamic SQL is harder to work with and is too often the only applicable solution to a problem that's caused by a fundamental flaw in the database design. – Zohar Peled Feb 14 '22 at 09:25
  • I also note you've asked many questions recently and not accepted any answers to them, is there a reason for that? – Stu Feb 14 '22 at 09:28
  • Isn't this effectively what you asked [before](https://stackoverflow.com/questions/70969968/how-to-create-a-table-using-column-names-present-in-another-table)? – Thom A Feb 14 '22 at 09:45
  • @Larnu The solution provided didnt work. – Tom Feb 14 '22 at 09:55
  • So edit the other question, or respond to the answers, don't repost the question... I've closed this as a dupe, as it seems it's a dupe. I posted an answer there, for example, and you have never commented that it "didn't work". – Thom A Feb 14 '22 at 09:55
  • @Stu I am just learning somethings and trying to figure out a way to complete my tasks. I cannot post my complete code here as it includes so many linked functions and stored procedures to it. – Tom Feb 14 '22 at 09:55
  • @Larnu This is not exactly duplicate. I am using a string here in this example. I will update the answer in my old thread as per your suggestion but this question asked here is in more simplified form. – Tom Feb 14 '22 at 10:07
  • Then the answer is "No", you must use dynamic SQL. And you have your solution how to do that in the other question. – Thom A Feb 14 '22 at 10:08

1 Answers1

0

In case you need a temp table with a structure, which includes only columns from your another source, you can do smth like this:

SELECT column1, ..., columnN
INTO #tmp
FROM Source
WHERE 1=0

But you won't be able to specify column's datatypes and constraints, they will be inherited from your Source table.

yoma
  • 359
  • 1
  • 7