在SQL Server存储过程中插入数据

时间:2015-01-06 15:10:43

标签: stored-procedures sql-server-2012

我正在尝试使用SQL Server存储过程在单个表中添加数据,但我收到错误

  

过程或函数x指定的参数太多

另外,我如何获取新创建的记录ID,因为我需要使用这些ID更新多个表

我正在使用SQL Server 2012

非常感谢

ALTER PROCEDURE [dbo].[CreateNewFunctionsNavigation]
   @FunctionName nvarchar(250),
   @Hierarchy_Level int
AS
BEGIN
   SET NOCOUNT ON;

   INSERT [dbo].[Navigation_Functions] ([FunctionName], [Hierarchy_Level])
   VALUES(@FunctionName, @Hierarchy_Level)
END

执行存储过程:

DECLARE @return_value int

EXEC    @return_value = [dbo].[CreateNewFunctionsNavigation]
        @FunctionName = N'DSD',
        @Hierarchy_Level = 3

SELECT  'Return Value' = @return_value
GO

我的SQL for Function表

USE [MySolution01_DB]
GO

/****** Object:  Table [dbo].[Navigation_Functions]    Script Date: 06/01/2015 15:58:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Navigation_Functions](
 [Function_ID] [int] IDENTITY(1,1) NOT NULL,
 [FunctionName] [nvarchar](250) NOT NULL,
 [Hierarchy_Level] [int] NOT NULL,
CONSTRAINT [PK_Functions] PRIMARY KEY CLUSTERED 
(
  [Function_ID] ASC
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,   ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

  GO

3 个答案:

答案 0 :(得分:1)

应该是

INSERT INTO [dbo].[Navigation_Functions] ([FunctionName], [Hierarchy_Level])

我创建了一个示例表

CREATE TABLE [dbo].[Navigation_Functions](
    [NavigationFunctionId] [int] IDENTITY(1,1) NOT NULL,
    [FunctionName] [nvarchar](250) NULL,
    [Hierarchy_Level] [int] NULL,
 CONSTRAINT [PK_Navigation_Functions] PRIMARY KEY CLUSTERED 
(
    [NavigationFunctionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

答案 1 :(得分:1)

您可以通过以下方式获取最后一个ID:SELECT SCOPE_IDENTITY();

答案 2 :(得分:0)

USE [MySolution01_DB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[CreateNewFunctionsNavigation]
  @FunctionName nvarchar(250),
  @Hierarchy_Level INT,
  @Function_identity INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;

INSERT INTO [dbo].[Navigation_Functions] ([FunctionName],[Hierarchy_Level] ) 
VALUES(@FunctionName, @Hierarchy_Level);

   SET @Function_identity=SCOPE_IDENTITY()
   RETURN @Function_identity

RETURN
END