I have a SQL table that shows the date and time information of a topic.
FirstTable
looks like this:
id | DateP | TimeP |
---|---|---|
1 | 1397/01/02 | 01:30 |
2 | 1398/05/09 | 05:30 |
3 | 1398/06/07 | 05:10 |
4 | 1398/08/09 | 06:12 |
5 | 1399/02/01 | 07:15 |
I want to create columns for another table that are the result of selecting the DateP column and the TimeP column from FirstTable.
SecondTable
looks like this:
id | EmployeeID | 1397/01/02_01:30 | 1398/05/09_05:30 | 1398/06/07_05:10 | 1398/08/09_06:12 | 1399/02/01_07:15 |
---|
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
Please guide me in finding the SQL code.
Advertisement
Answer
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 ISNULL(DateP,'') + '_'+ISNULL(TimeP,'') FROM FirstTable where id=@i) exec ('ALTER TABLE SecondTable ADD ['+@DatTim +'] int NULL') SET @i = @i + 1; END