The following code will help you but sp_executesql statment create the temp table in the other session for this reason you can use global temp table.
DROP TABLE IF EXISTS ##Test
DECLARE @tbl_query as NVARCHAR(MAX) = 'CREATE TABLE ##Test ( '
DECLARE
@tablecol VARCHAR(300),
@tablettype VARCHAR(300) ,
@typelengt VARCHAR(300)
DECLARE cursor_product CURSOR
FOR sELECT
c.name 'Column Name',
t.Name 'Data type' ,
IIF(t.name = 'nvarchar', c.max_length / 2, c.max_length)
FROM
sys.columns c
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
c.object_id = OBJECT_ID('your_table_name')
and ISNULL(i.is_primary_key, 0)=1
OPEN cursor_product;
FETCH NEXT FROM cursor_product INTO
@tablecol,
@tablettype,
@typelengt
WHILE @@FETCH_STATUS = 0
BEGIN
IF @tablettype LIKE '%varchar%'
BEGIN
SET @typelengt = '(' + @typelengt + ')'
END
ELSE
BEGIN
SET @typelengt=''
END
set @tbl_query = @tbl_query + @tablecol + ' ' + @tablettype + @typelengt + ' , '
FETCH NEXT FROM cursor_product INTO
@tablecol,
@tablettype,
@typelengt
END;
CLOSE cursor_product;
DEALLOCATE cursor_product;
SET @tbl_query = SUBSTRING(@tbl_query,1,LEN(@tbl_query)-1)
SET @tbl_query = @tbl_query + ' )'
PRINT @tbl_query
EXEC sp_executesql @tbl_query