我有这个程序,我想要将值列表插入表中,我想检查重复值并返回此但我收到此错误
ERROR:
子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
ALTER PROCEDURE [dbo].[insertData]
@Value insertTbl READONLY,
@Result INT OUTPUT
AS
BEGIN
BEGIN TRY
IF (SELECT COUNT(Id)
FROM @Values
WHERE Id IN (SELECT Id
FROM [dbo].[username])) = 0
BEGIN
INSERT INTO dbo.username ( Id, NAME )
SELECT Id,
NAME
FROM @Values
WHERE Id NOT IN (SELECT Id
FROM [dbo].[username])
SELECT @Result = 101
END
ELSE
SELECT @Result = (
SELECT Id
FROM @Values
WHERE Id IN (SELECT Id
FROM [dbo].[username])
)
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE()
END CATCH
END
答案 0 :(得分:2)
请试试这个。
我已将返回类型更改为VARCHAR。这将返回CSV(例如1,3,9 ...)
另一种选择是返回结果集。为此,将SELECT @Result =
替换为INSERT INTO @Result...
希望这有帮助。
ALTER PROCEDURE [dbo].[insertData]
@Value insertTbl READONLY,
@Result VARCHAR(500) OUTPUT
AS
BEGIN
BEGIN TRY
IF (SELECT COUNT(Id)
FROM @Values
WHERE Id IN (SELECT Id
FROM [dbo].[username])
) = 0
BEGIN
INSERT INTO dbo.username (Id,NAME)
SELECT Id,
NAME
FROM @Values
WHERE Id NOT IN (SELECT Id
FROM [dbo].[username])
SELECT @Result = 101
END
ELSE
BEGIN
SELECT @Result = (SELECT STUFF((SELECT ', ' + CAST(ID AS VARCHAR(5))
FROM @Values
WHERE Id IN (SELECT Id
FROM [dbo].[username])
ORDER BY Id FOR XML PATH('')),1,2,''))
END
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE()
END CATCH
END
答案 1 :(得分:1)
可能是这一行
SELECT @Result=(SELECT Id FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username]))
返回多行。您应该更改查询以仅返回一个值,如下所示
SELECT @Result=(SELECT top 1 Id FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username]))
或者你应该改变你的逻辑。另一种方法是使用temprary表返回ID的listo。尝试以下解决方案
-- create temporary table before (!) creating procedure
create table #Resulttab
(
Result int
)
go
ALTER PROCEDURE [dbo].[insertData]
@Value insertTbl READONLY,
@Result INT OUTPUT -- in this solution I think you don't need this parameter
AS
BEGIN
BEGIN TRY
IF (SELECT COUNT(Id)
FROM @Values
WHERE Id IN (SELECT Id
FROM [dbo].[username])) = 0
BEGIN
INSERT INTO dbo.username ( Id, NAME )
SELECT Id,
NAME
FROM @Values
WHERE Id NOT IN (SELECT Id
FROM [dbo].[username])
SELECT @Result = 101
END
ELSE
insert into #Resulttab
SELECT Id
FROM @Values
WHERE Id IN (SELECT Id
FROM [dbo].[username])
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE()
END CATCH
END
go
您可以这样使用:
-- create temporary table before run procedure
create table #Resulttab
(
Result int
)
-- run procedure with parameters
exec insertData ...
--after run procedure you can check list of your IDs
select Result from #Resulttab