简体   繁体   English

无法将表值函数的结果分配给表变量

[英]Can't assign result of table valued function to table variable

I have this function: 我有这个功能:

Create function [dbo].[Split]
(
    @String nvarchar(max)
)
returns @SplittedValues table
(
    Id nvarchar(50) primary key
)

In a stored procedure, I am trying to take the result of this functions invocation and insert it into a table variable: 在存储过程中,我尝试获取此函数调用的结果并将其插入表变量中:

DECLARE @SplittedValues table
(
    [Id] nvarchar(50) primary key
);
INSERT INTO @SplittedValues([Id])
VALUES (SELECT * FROM [dbo].[Split](@Commands);

I get 我懂了

Incorrect Syntax near "SELECT" “ SELECT”附近的语法不正确

DB version is SQl Server 2012 数据库版本为SQl Server 2012

The error message is misleading. 该错误信息是令人误解的。 If you really wanted to use (scalar!) subselects in the INSERT .. VALUES() clause, you'd have to add additional parentheses: 如果您确实想在INSERT .. VALUES()子句中使用(scalar!)子选择,则必须添加其他括号:

INSERT INTO @SplittedValues([Id])
VALUES ((SELECT * FROM ...));

That would be the "correct" syntax. 那将是“正确的”语法。 But in your case, that doesn't make sense anyway. 但是,就您而言,这毫无意义。 You want to copy the outcome of the SELECT into the @SplittedValues table as a whole. 您希望将SELECT的结果整体复制到@SplittedValues表中。 So, try this instead: 因此,请尝试以下操作:

INSERT INTO @SplittedValues([Id])
SELECT * FROM [dbo].[Split](@Commands);

Your syntax is incorrect. 您的语法不正确。 It should be 它应该是

INSERT INTO @SplittedValues([Id])
SELECT * FROM [dbo].[Split](@Commands)

Syntax insert into table_name (columns_list) values (values_list) should be used when you have some finite values list written in your query. 当您在查询中写入一些有限值列表时,应使用语法insert into table_name (columns_list) values (values_list)

But when you're inserting from resultset obtained from some select, it shold be insert into table_name (columns_list) select values from another_table 但是,当您从某些select获得的结果insert into table_name (columns_list) select values from another_table进行insert into table_name (columns_list) select values from another_table ,它被insert into table_name (columns_list) select values from another_table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM