我遇到了尝试使此查询工作的问题,我不断收到错误,这是代码,然后是相关的错误
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ConcatNames]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
EXECUTE dbo.sp_executesql @statement = N'
create function dbo.ConcatNames(@ProdId int) returns varchar(8000)
as
begin
declare @output varchar(8000)
select @output = coalesce(@output + ', ', '') + Name
from Reports
where ProdID = @ProdId and Name > ''
return @output
end'
PRINT N'Created function ConcatNames'
END
ELSE
BEGIN
PRINT N'function ConcatAttributeNames Already Exists'
END
错误
Msg 119,Level 15,State 1,Line 8
的形式传递
必须将参数编号2和后续参数传递为' @name = value'。
表格' @name = value'已被使用,所有后续参数 必须以' @name = value'。
答案 0 :(得分:6)
SQL Server将此视为一个代码块,因此“创建函数”将失败。因此,在做了贾斯汀建议之后你得到的错误。
要这样做(打印消息等),你必须按照最初的方式执行语句。除非您必须先设置文本:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ConcatAttributeNames]') AND
type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
declare @statement nvarchar(4000)
set @statement = N'
create function [dbo].[ConcatAttributeNames] (@prodId int) returns varchar(8000)
as
begin
declare @output varchar(8000)
select @output = coalesce(@output + '', '', '''') + AttributeName
from Report_Attribute
where ProdID = @ProdId and AttributeName > ''''
return @output
end '
exec sp_executesql @statement
PRINT N'Created function ConcatAttributeNames'
END
ELSE
BEGIN
PRINT N'function ConcatAttributeNames Already Exists'
END
此外,由于您要传递此声明,因此必须对单引号进行转义以避免错误。