V
V
Vladimir2022-01-18 12:41:26
SQL Server
Vladimir, 2022-01-18 12:41:26

Why is the temporary table not dynamically created in the procedure?

The stored procedure dynamically creates columns in a temporary table. On the first run a column named "Column1" is created, on the next run "Column2" , i.e. column name - calculated.

EXEC _test1 'column1'
EXEC _test1 'column2'
EXEC _test1 'column3'

But in fact, on the second and third hits, the table shows the 'column1' column - even if I open a new SSMS window or start a new instance of SSMS .
dbo._test1
CREATE procedure dbo._test1(
  @name varchar( 32)
)
AS 
BEGIN
  Select SPID = @@SPID

  if object_id('tempdb..#TST') is not null				Select  'temp table #TST exists on start'

  Create table #TST(	dummy varchar(32) NULL	)

  Select *  from #tst

Declare @SQLString varchar(255)
  SET @SQLString = 'ALTER  TABLE #TST add [' + @name +  '] varchar(255) null '
  EXEC ( @SQLString )

  Select *  from #tst

  drop table #TST

  if object_id('tempdb..#TST') is not null			Select  'temp table #TST exists on STOP'
END

It is completely unclear where the old column name appears in the temporary table when the "second" call comes from? On older 2000 - 2014 versions of SQL, this problem did not occur. The problem manifests itself on Microsoft SQL Server 2019.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Tsvetkov, 2022-01-18
@TroubleInThat

SELECT @@VERSION
GO
EXEC _test1 'column1'
GO
EXEC _test1 'column2'
GO
EXEC _test1 'column3'
GO

Result
Microsoft SQL Server 2019 (RTM-CU14) (KB5007182) - 15.0.4188.2 (X64) 

(затронута одна строка)

SPID
------
60

(затронута одна строка)

dummy
--------------------------------

(затронуто строк: 0)

dummy                            column1
-------------------------------- ---------

(затронуто строк: 0)

SPID
------
60

(затронута одна строка)

dummy
--------------------------------

(затронуто строк: 0)

dummy                            column2
-------------------------------- ---------

(затронуто строк: 0)

SPID
------
60

(затронута одна строка)

dummy
--------------------------------

(затронуто строк: 0)

dummy                            column3
-------------------------------- ---------

(затронуто строк: 0)


Время выполнения: 2022-01-18T13:20:25.1207006+03:00

V
Vladimir, 2022-01-18
@TroubleInThat

Problem solved.
Cumulative update CU14 installed
SQL version updated to
Microsoft SQL Server 2019 (RTM-CU14) (KB5007182) - 15.0.4188.2 (X64) Nov 3 2021 19:19:51 Copyright (C) 2019 Microsoft Corporation Standard Edition (64-bit) on Windows 10 Enterprise 10.0 (Build 19042: )
Thanks for the tip.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question