I am trying to create a stored procedure on SQL Server 2008, I get an error:
Msg 156, Level 15, State 1, Procedure usp_UpdateDistribiutionList, Line 12 Incorrect syntax near the keyword 'AS'.
Can you advise?
Stored procedure code:
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
2nd question:
is it possible to use parameter to get column name like dist.@columnName?
Remove the AS
in the UPDATE
statement, and put it in the FROM
clause instead, it should be:
UPDATE dist
SET dist.emailCC = @DistEmails
FROM [NotificationDistribution] AS dist
WHERE dist.DistributionID = @distId
For your second question, you can't do this like that, you have to do this dynamically using dynamic SQL.
Change your UPDATE to the following:
UPDATE [NotificationDistribution]
SET emailCC = @DistEmails
WHERE DistributionID = @distId
If you want to do it Dynamic:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.