我正在嘗試做一個內部使用過程只有它的一部分,你可以添加一個由逗號分隔的標籤的字符串。字符串拆分只返回第一個條目
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE AddService
@ServiceName AS VARCHAR(MAX),
@Location AS VARCHAR(MAX),
@Description AS VARCHAR(MAX),
@PermissionType AS INT,
@Tags AS VARCHAR(MAX)
AS
BEGIN
DECLARE @ServiceId AS INT
INSERT INTO Services(NAME,LOCATION,DESCRIPTION,PERMISSIONTYPE) VALUES(@ServiceName,@Location,@Description,@PermissionType)
SET @ServiceId = (SELECT SCOPE_IDENTITY())
DECLARE @TagSplit TABLE(ID INT IDENTITY(1,1),DATA VARCHAR(MAX))
INSERT @TagSplit VALUES(SUBSTRING(@Tags,0,CHARINDEX(',',@Tags)))
WHILE EXISTS(SELECT * FROM @TagSplit)
BEGIN
DECLARE @TempId AS INT
DECLARE @Tag AS VARCHAR(MAX)
SET @TempId = (SELECT TOP 1 ID FROM @TagSplit)
SET @Tag = (SELECT TOP 1 DATA FROM @TagSplit)
INSERT INTO Tags VALUES(@ServiceId,@Tag)
DELETE FROM @TagSplit WHERE ID = @TempId
END
END
GO
但是,當我看着我的「標籤」表中,給出的@Tags
字符串「一些事」只能「部分」被添加,但不是「東西」。我想我可能會誤解如何在SQL中進行正確的字符串分割。
這部分不正常工作:
WHILE EXISTS(SELECT * FROM @TagSplit)
BEGIN
DECLARE @TempId AS INT
DECLARE @Tag AS VARCHAR(MAX)
SET @TempId = (SELECT TOP 1 ID FROM @TagSplit)
SET @Tag = (SELECT TOP 1 DATA FROM @TagSplit)
INSERT INTO Tags VALUES(@ServiceId,@Tag)
DELETE FROM @TagSplit WHERE ID = @TempId
END
任何幫助嗎?
爲什麼不使用的數據類型* *設計用於容納多個值,如表或XML,而不是給自己包含逗號的字符串? –
@Damien_The_Unbeliever我只是覺得這很容易,因爲這將被使用的方式只需右鍵單擊數據庫管理器中的過程,然後單擊「執行」。 – OmniOwl