我的数据库中有名为Table_Stories
和Table_Images
的表,它们通过键连接。我使用创建的存储过程将值插入其中。
CREATE TABLE [dbo].Table_Stories
(
[StoryID] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[ID] INT FOREIGN KEY REFERENCES Table_Users(ID),
[StoryText] NVARCHAR(120),
[imgID] INT FOREIGN KEY REFERENCES Table_Images (imgID)
)
代码:
CREATE PROCEDURE UserStory
@ID [INT],
@storyText [NVARCHAR](120),
@img [VARCHAR](MAX)
AS
BEGIN
DECLARE @StoryID INT, @ImageID INT;
INSERT INTO Table_Images ([img]) VALUES (@img)
SET @ImageID = SCOPE_IDENTITY();
INSERT INTO Table_Stories ([ID], [StoryText], [imgID])
VALUES (@ID, @storyText, @ImageID)
SET @StoryID = SCOPE_IDENTITY();
INSERT INTO Table_Stories ([StoryID])
VALUES (@StoryID)
INSERT INTO dbo.imagesInStories (StoryID, imgID)
VALUES (@StoryID, @ImageID);
SELECT *
FROM Table_Stories
WHERE StoryID = @StoryID AND imgID = @ImageID;
END
我跑步:
exec UserStory 1, 'I welcom you to my trip', 'Chadmie.jpg'
并得到此错误:
消息545,级别16,状态1,过程UserStory,行14 [批处理开始行291]
当IDENTITY_INSERT设置为ON或将复制用户插入到NOT FOR REPLICATION身份列中时,必须为表'Table_Stories'中的身份列指定显式值。
我不明白该错误的含义以及解决方法。
p.s 我无法在此处插入所有sql代码(不是我所做的那样),因为红色错误会占用我太多时间,无论我如何尝试解决问题代码,该错误都会显示出来。
答案 0 :(得分:0)
我的建议:
ID
重命名为UserID
-表UserStory
的名称现在非常混乱Table_Stories
中-我不知道为什么要为此写EditUserStory
或UserStory_UPD
之类的东西dbo
,请指定对象的架构事件,不要使用select *
例如
CREATE PROCEDURE dbo.UserStory_UPD
@UserID INT,
@storyText NVARCHAR(120),
@img VARCHAR(MAX) -- I assume this is a path or an URL
AS
BEGIN
DECLARE @StoryID INT, @ImageID INT;
BEGIN TRY
/* params validation stuff */
BEGIN TRAN
INSERT INTO dbo.Table_Images ([img])
VALUES (@img)
SET @ImageID = SCOPE_IDENTITY();
INSERT INTO dbo.Table_Stories ([UserID], [StoryText], [imgID])
VALUES (@UserID, @storyText, @ImageID)
SET @StoryID = SCOPE_IDENTITY();
INSERT INTO dbo.imagesInStories (StoryID, imgID)
VALUES (@StoryID, @ImageID);
COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN
/* raiserror stuff or THROW */
END CATCH
SELECT s.StoryID, s.UserID, s.StoryText, s.ImgID
FROM dbo.Table_Stories s
WHERE s.StoryID = @StoryID
END