I have run into a little bit of a problem: I want to create a procedure that inserts some rows in a table specified via parameter. So along the code I have reached this point:
CREATE PROCEDURE my_proc @tableName VARCHAR(30)
AS
-- ...some code...
INSERT INTO @tableName VALUES(...some values...)
-- ...some code...
GO
This doesn't work so maybe I'm missing something.
PS: I'm working in Microsoft SQL Server Management Studio 2018
You can only use variables for constants in a query -- not for identifiers. So, you need to use dynamic SQL:
declare @sql nvarchar(max);
set @sql = 'insert into [tablename] values ( . . . )';
set @sql = replace(@sql, '[tablename]', quotename(tablename));
exec sp_executesql @sql;
Two points. First, if you are planning in on passing the table name using a multi-part identifier, then quotename()
is not appropriate.
More importantly, passing table names around like this is almost never needed in a relational database. If you find the need to do this, you likely have a problem with your data model. I would guess that you have multiple tables with the same structure -- and these should be combined into a single table rather than multiple tables.
To handle quotes strings:
set @sql = 'insert into [tablename] values (''aaa'', ''bbb'', . . . )';
Those are repeated single quotes ( ''
), not double quotes ( "
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.