构建将数据插入接收到的存储过程 table
Build Stored Procedure that inserts data into a received table
我构建了一个过程,该过程接收名称为 table 的参数,并向该 table 插入新数据。
CREATE PROCEDURE sp_Ins
@tabela NVARCHAR(80)
AS
INSERT INTO @tabela (CustomerID, CustomerPW)
VALUES (1, '123')
GO
CREATE PROCEDURE SP1
@tabela NVARCHAR(80)
AS
EXEC sp_Ins @tabela
GO
EXEC SP1 'CustomerPW'
但我收到这条消息:
Must declare the table variable @tabela
如何声明接收到的参数以将参数识别为 table?
抱歉,您需要使用动态SQL。您不能插入到字符串中:
CREATE PROCEDURE sp_Ins (@tabela nvarchar(80))
AS
BEGIN
declare @sql nvarchar(max) = '
INSERT INTO [t](CustomerID, CustomerPW)
VALUES (1, ''123'')
;
set @sql = replace(@sql, '[t]', QUOTENAME(@tablea));
exec sp_executesql @sql;
END;
注意:如果 tablea
可以使用多部分命名,您可能不需要 quotename()
。
我构建了一个过程,该过程接收名称为 table 的参数,并向该 table 插入新数据。
CREATE PROCEDURE sp_Ins
@tabela NVARCHAR(80)
AS
INSERT INTO @tabela (CustomerID, CustomerPW)
VALUES (1, '123')
GO
CREATE PROCEDURE SP1
@tabela NVARCHAR(80)
AS
EXEC sp_Ins @tabela
GO
EXEC SP1 'CustomerPW'
但我收到这条消息:
Must declare the table variable @tabela
如何声明接收到的参数以将参数识别为 table?
抱歉,您需要使用动态SQL。您不能插入到字符串中:
CREATE PROCEDURE sp_Ins (@tabela nvarchar(80))
AS
BEGIN
declare @sql nvarchar(max) = '
INSERT INTO [t](CustomerID, CustomerPW)
VALUES (1, ''123'')
;
set @sql = replace(@sql, '[t]', QUOTENAME(@tablea));
exec sp_executesql @sql;
END;
注意:如果 tablea
可以使用多部分命名,您可能不需要 quotename()
。