我正在尝试在SQL Server 2008上创建存储过程,我收到错误:
你可以建议吗?Msg 156,Level 15,State 1,Procedure usp_UpdateDistribiutionList, 第12行关键字“AS”附近的语法不正确。
存储过程代码:
USE LogDB
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE usp_UpdateDistribiutionList
-- Add the parameters for the stored procedure here
@distId INT,
@DistEmails varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE [NotificationDistribution] AS dist
SET dist.emailCC = @DistEmails
WHERE dist.DistributionID = @distId
END
第二个问题:
是否可以使用参数获取列名,如dist。@ columnName?
答案 0 :(得分:3)
删除AS
语句中的UPDATE
,并将其放在FROM
子句中,它应该是:
UPDATE dist
SET dist.emailCC = @DistEmails
FROM [NotificationDistribution] AS dist
WHERE dist.DistributionID = @distId
对于您的第二个问题,您不能这样做,您必须使用动态SQL动态执行此操作。
答案 1 :(得分:1)
将您的更新更改为以下内容:
UPDATE [NotificationDistribution]
SET emailCC = @DistEmails
WHERE DistributionID = @distId
如果你想这样做动态:
CREATE PROCEDURE usp_UpdateDistribiutionList
-- Add the parameters for the stored procedure here
@distId INT,
@DistColumn varchar(max),
@DistValue varchar(max)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQL AS NVARCHAR(MAX)
SET @SQL =
N'UPDATE [NotificationDistribution]
SET ' + QuoteName(@DistColumn ) + ' = @DistValue
WHERE DistributionID = @distId'
EXECUTE sp_executesql
@SQL,
N'@DistValue varchar(max), @distId INT',
@DistValue = @ColumnValue,
@distId = @distId
END