0

I'm creating a SQL Server table via a trigger, and I want the table name to be specific each time.

For the end result, I want the table name to be tblTEMP_INA_DATA_12345.

I could obviously, just type tblTEMP_INA_DATA_12345, but the @PlanID value will be different each time.

How could I modify the create table statement to do what I want? Is this possible?

I have searched, but I'm not sure what search terms to even use. I appreciate any and all responses even if the answer is no.

DECLARE @PlanID varchar(80)

SET @PlanID = 12345

CREATE TABLE [dbo].[tblTEMP_INA_DATA_]
(
    [strQuestion] [varchar](max) NULL,
    [strAnswer] [varchar](max) NULL
) ON [PRIMARY]
3
  • 2
    Since you can't do this directly, you can either 1. Use dynamic SQL or 2. Create the table without the suffix and then use sp_rename to rename it Commented Sep 5, 2022 at 5:42
  • 1
    Creating a table inside a trigger seems like a really BAD idea .... Commented Sep 5, 2022 at 6:03
  • @marc_s I don't disagree with you at all. Commented Sep 5, 2022 at 6:12

1 Answer 1

2

You can use dynamic sql to do this. Like below

Declare @PlanID varchar(80),@sql nvarchar(max);

Set @PlanID = 123456

set @sql= 'Create TABLE [dbo].' + QUOTENAME('tblTEMP_INA_DATA_' + @PlanID) + '
([strQuestion] [varchar](max) NULL,

[strAnswer] [varchar](max) NULL
)  ON [PRIMARY]'

exec (@sql);
Sign up to request clarification or add additional context in comments.

1 Comment

This did exactly what I wanted. I appreciate your help immensely. Now to test any and all scenarios to see if I run into any unforeseen issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.