Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table that shows the date information of a topic.

`FirstTable` looks like this:

|id|DateP|
|---|---|
|1|1397/01/02|
|2|1398/05/09|
|3|1398/06/07|
|4|1398/08/09|
|5|1399/02/01|

I want to create columns for another table that are the result of selecting the DateP column from FirstTable.

`SecondTable` looks like this:

|id|1397/01/02|1398/05/09|1398/06/07|1398/08/09|1399/02/01|
|---|---|---|---|---|---|
|1||||||
|2||||||
|3||||||

Please guide me in finding the SQL code.


What I have tried:

DECLARE @i INT = 0;
DECLARE @DatTim NVARCHAR(50)='';
SELECT @count=  Count(*) FROM FirstTable

WHILE @i <= @count
BEGIN
    @DatTim=(select DateP+TimeP FROM FirstTable where id=@i)   
    ALTER TABLE SecondTable ADD @DatTim NVARCHAR(50);
    SET @i = @i + 1;
END
Posted
Updated 21-Sep-21 11:53am

Thanks to the members, thank God, I was able to find a solution:


DECLARE @i INT = 1;
DECLARE @count INT = 0;
DECLARE @DatTim NVARCHAR(50)='';
Set @count=(select Count(*) FROM FirstTable)

WHILE @i <= @count
BEGIN
    Set @DatTim=(select DateP FROM FirstTable where id=@i)   
    exec ('ALTER TABLE SecondTable ADD ['+@DatTim +'] int NULL')
    SET @i = @i + 1;
END
 
Share this answer
 
This is idempotent and with no loops. Good luck!

SQL
/*
CREATE TABLE dbo.FirstTable (id INT, DateP DATE);

INSERT INTO dbo.FirstTable (id, DateP)
VALUES (1,'1397/01/02')
,(2,'1398/05/09')
,(3,'1398/06/07')
,(4,'1398/08/09')
,(5,'1399/02/01');
*/

IF OBJECT_ID(N'dbo.SecondTable') IS NULL
	CREATE TABLE dbo.SecondTable (id INT NOT NULL IDENTITY PRIMARY KEY);

DECLARE @tsql NVARCHAR(MAX) = N'';

SELECT @tsql = @tsql + N'
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N''dbo.SecondTable'') AND name = N''' + CONVERT(NVARCHAR(10), DateP, 111) + ''')
	ALTER TABLE dbo.SecondTable ADD [' + CONVERT(NVARCHAR(10), DateP, 111) + N'] NVARCHAR(50);'
FROM dbo.FirstTable
ORDER BY id;

PRINT @tsql;
EXEC sys.sp_executesql @tsql;
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900