using SQL Azure and like to insert a data to a table using dynamic Query.
No of columns in select statment is dynamic. It will be based on some conditions.
How can I create a table for conditional based columns and do insert in coditions?
I don't want to use SELECT INTO #tempTable as it is not supporting in SQL Azure
Here is the code:
DECLARE @sql NVARCHAR(MAX) ,@sqlSelect NVARCHAR(MAX) = '' ,@sqlFrom NVARCHAR(MAX) ='' CREATE TABLE #myTempTable (Id INT, DeptId INT, DeptName VARCHAR(100)) SET @sqlSelect ='INSERT INTO #myTempTable SELECT EMP.Id, EMP.DeptId, EMP.DeptName' SET @sqlFrom =' FROM dbo.EMPLOYEE AS EMP' IF (someCondition) BEGIN SET @sqlSelect = @sqlSelect +', EMP.Salary, EMP.Code' END SET @sql = @sqlSelect +@sqlFrom EXEC sp_executesql @sql