Mssql: insert into table with dynamic name in variable - sql

I'm working with dynamic table name in variable, as example
#tableName varchar(512) = master.dbo.TableName'
I can work with it in dynamic code, like that:
DECLARE #sqlCode varchar(max) = CONCAT('
CREATE TABLE ',#tableName,(
Id Integer identity (1,1) not null,
Name varchar(512) not null
);
';
EXEC (#sqlCode);
I can insert data only in dynamic code or another way?

Related

Create SQL Server table name that includes a variable value

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]
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);

Cannot return a user table type form a function

I just wrote this coe example to return a user type from a function:
CREATE TYPE dbo.ScheduledActivity_TVP AS TABLE
(
Id uniqueidentifier NOT NULL primary key,
AdditionalDataTypeSignature nvarchar(100) not null,
AdditionalDataId uniqueidentifier NOT NULL,
AdmissionId uniqueidentifier NOT NULL
)
GO
CREATE OR ALTER function [dbo].[Fun_GetFollowUpBymonth](#admissionId uniqueidentifier)
returns ScheduledActivity_TVP as
begin
declare #q ScheduledActivity_TVP
insert into #q
select Id,
AdditionalDataTypeSignature,
AdditionalDataId,
AdmissionId
from ScheduledActivities
where #admissionId = ScheduledActivities.AdmissionId;
return #q
GO
And Sql Server tells me that I must declare the scalar variable #q.
What is wrong in the code above?
I don't see why you are using a multi-line table value function here; they are notoriously slow.
Use an inline table value function, which doesn't even need a TYPE:
CREATE OR ALTER FUNCTION [dbo].[Fun_GetFollowUpBymonth] (#admissionId uniqueidentifier)
RETURNS table
AS RETURN
SELECT Id,
AdditionalDataTypeSignature,
AdditionalDataId,
AdmissionId
FROM dbo.ScheduledActivities
WHERE #admissionId = ScheduledActivities.AdmissionId;

Get a list of inserted ids as a result set from a stored procedure T-SQL

I have generated a stored procedure that inserts values to the ITEM table from JSON string.
Just like that:
CREATE PROCEDURE SP_INSERT_JSON
#J NVARCHAR(MAX)
AS
BEGIN
SET IDENTITY_INSERT ITEM ON;
INSERT INTO ITEM (ITEM_ID, TITLE, DESCRIPTION)
SELECT (SELECT IDENT_CURRENT('ITEM') + 1), *
FROM OPENJSON(#J, '$')
WITH(
Title NVARCHAR(MAX) '$.Title',
Description NVARCHAR(MAX) '$.Description'
)
SET IDENTITY_INSERT ITEM OFF;
END
Also, what I want now is to return a list of inserted IDs as a result set from this stored procedure. I've tried to combinate it with an OUTPUT clause in different ways but it never worked. Any idea how to do this?
CREATE TABLE [ITEM]
(
[ITEM_ID] INT IDENTITY(1,1) NOT NULL,
[TITLE] VARCHAR(255) NULL,
[DESCRIPTION] VARCHAR(255) NULL,
CONSTRAINT PK__ITEM PRIMARY KEY CLUSTERED ([ITEM_ID] ASC)
)
JSON STRING: N'[{"Title" : "Introduction to Computers","Description" : "Computer literacy. Basic Computer Concepts."}]'
I'm not sure why you are inserting into the Identity column, you don't need to just don't include it in the column list.
You can output the newly inserted Item_Id using output:
insert into ITEM (TITLE, DESCRIPTION)
output inserted.ITEM_ID
select Title, Description
from OpenJson(#j, '$')
with(
Title nvarchar(max) '$.Title',
Description nvarchar(max) '$.Description'
)
See demo Fiddle
Also note that prefixing procedures with sp_ is not recommended, System Procedures are reserved by Microsoft.

I need to create a SQL table using dynamic SQL

I am trying to write a stored procedure in SSMS that creates a table, along with two columns with the subject of the table as the single parameter. The table must be named t followed by the subject of the table. As for the columns, the first column is an auto-incrementing surrogate key ID field (and the primary key) that is named as the subject of the table, followed by ID.
The second column is a natural key which is named as the subject of the table. For instance, a table to be created with the subject being Student would create a table named tStudent, with a StudentID surrogate key column as well as a natural key column named Student. I am trying to do this using a dynamic SQL statement (which I am new to) and keep running into issues while trying to implement my natural key column.
ALTER PROC spCreateTable
#subjectOfTable varchar(50)
AS
DECLARE #dynamicSQL nvarchar(500),
#tableName varchar(50),
#tableID varchar(50);
SET #tableName = ('t' + #subjectOfTable);
SET #tableID = (#subjectOfTable + 'ID');
SET #dynamicSQL = 'CREATE TABLE ' + #tableName + ' ( '+ #tableID + ' INT NOT NULL PRIMARY KEY IDENTITY(1,1) ' + #subjectOfTable + ' VARCHAR(50) ) ';
EXEC (#dynamicSQL)
GO
I can get it to work correctly while just adding the tableID column, but keep having syntax issues with the natural key column subjectOfTable. Someone please help!

How can I pass tables to stored procedures?

I have a table of data like this, and one procedure is going to populate data in it like this,
DECLARE #ClaimChanges TABLE (
ChangeType NVARCHAR(10)
,contract_id int NOT NULL
,dispatch_id int NOT NULL
,dispatch_claim_id int NOT NULL
,item_no VARCHAR(100) NULL
,old_units VARCHAR(100) NULL
);
I would then like to pass that data to a different stored procedure which would be defined like this,
CREATE procedure [dbo].[ct_audit_oncost](
#table TABLE readonly,
#OutValue nvarchar(255) = null output
)
as
-- some stuff
go
I gather this is not possible as I am getting an error,
Incorrect syntax near the keyword 'TABLE'.
Table valued parameters are supported since 2008 version.
However, you can't just pass any table you want, first you need to define a user defined table type:
CREATE TYPE dbo.MyUDT as TABLE
(
ChangeType NVARCHAR(10)
,contract_id int NOT NULL
,dispatch_id int NOT NULL
,dispatch_claim_id int NOT NULL
,item_no VARCHAR(100) NULL
,old_units VARCHAR(100) NULL
)
Then you can use it in your stored procedure:
CREATE procedure [dbo].[ct_audit_oncost]
(
#table dbo.MyUDT readonly,
#OutValue nvarchar(255) = null output
)
as
-- some stuff
go
Please note you should also use it to declare the table to send to the database:
DECLARE #Out nvarchar(255)
DECLARE #ClaimChanges as dbo.MyUdt
INSERT INTO #ClaimChanges (ColumnsList) VALUES (ValuesList)
EXEC ct_audit_oncost #ClaimChanges, #Out output