存储过程发出错误

时间:2013-09-08 10:21:48

标签: sql sql-server stored-procedures

我正在尝试在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?

2 个答案:

答案 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