my SQL
is:
SELECT DB1.IdUtente
,DB2.Gruppo
,DB1.Username
,DB1.Psw
,CASE WHEN DB1.RagioneSociale IS NOT NULL
AND DB1.RagioneSociale <> ''
THEN DB1.RagioneSociale
ELSE DB1.Cognome + ' ' + DB1.Nome
END AS Nominativo
,DB1.Indirizzo + ' - ' + DB1.Cap+ ' ' + DB1.Citta + '(' + DB1.Provincia + ')' AS IndirizzoCompleto
,DB1.Telefono + ' ' + DB1.Email AS Contatti
,(SELECT DISTINCT COUNT (*)
FROM DB3
WHERE DB3.IdAttivazione = DB1.IdUtente
) AS NumeroAccessi
,(SELECT DB4.NumTarga
FROM DB4
WHERE DB4.IdUtente = DB1.IdUtente
) AS NumeroTarghe
,DB1.DataRegistrazione
,DB1.DataScadenza
,DB1.Attivo
FROM DB1
INNER JOIN DB2
ON DB1.IdGruppo = DB2.IdGruppo
WHERE DB1.Demo = 0
ORDER BY DB1.RagioneSociale
Why i receive this error from sql server?
Error 512: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
What am i wrong?
Sorry for bad english.
Thanks for any help
Kind Regards
M.W.
iamdave
12k3 gold badges24 silver badges53 bronze badges
asked Jan 19, 2017 at 10:43
6
Your sub-selects should be rewritten as join
s even if your code was working without issue.
If you do this and actually do some testing across your whole dataset you will see where your duplication is coming from, which is giving you more than one row and causing the error you are seeing:
SELECT DB1.IdUtente
,DB2.Gruppo
,DB1.Username
,DB1.Psw
,CASE WHEN DB1.RagioneSociale IS NOT NULL
AND DB1.RagioneSociale <> ''
THEN DB1.RagioneSociale
ELSE DB1.Cognome + ' ' + DB1.Nome
END AS Nominativo
,DB1.Indirizzo + ' - ' + DB1.Cap+ ' ' + DB1.Citta + '(' + DB1.Provincia + ')' AS IndirizzoCompleto
,DB1.Telefono + ' ' + DB1.Email AS Contatti
,DB3.NumeroAccessi
-- Somewhere in your data you will have at least two rows with different values in this field.
,DB4.NumTarga AS NumeroTarghe
,DB1.DataRegistrazione
,DB1.DataScadenza
,DB1.Attivo
FROM DB1
INNER JOIN DB2
ON DB1.IdGruppo = DB2.IdGruppo
INNER JOIN (SELECT IdAttivazione
,COUNT(*) as NumeroAccessi
FROM DB3
GROUP BY IdAttivazione
) DB3
ON DB3.IdAttivazione = DB1.IdUtente
INNER JOIN DB4
ON DB4.IdUtente = DB1.IdUtente
WHERE DB1.Demo = 0
ORDER BY DB1.RagioneSociale
answered Jan 19, 2017 at 13:48
iamdaveiamdave
12k3 gold badges24 silver badges53 bronze badges
0
I’m getting the title’s error message when trying to determine the status of high availability databases on a particular cluster.
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression
Here is part of my code. I need to be able to utilize the results from both select statements and then assign @HadrRole
if both are met.
IF ((SELECT ars.role
FROM sys.dm_hadr_availability_replica_states ars
INNER JOIN sys.databases dbs
ON ars.replica_id = dbs.replica_id
WHERE dbs.name = @DatabaseName) = 2 AND (SELECT secondary_role_allow_connections_desc
FROM sys.availability_replicas) ='ALL')
SET @HadrRole = 3
marc_s
734k176 gold badges1332 silver badges1460 bronze badges
asked Jan 28, 2014 at 20:29
1
Try to use EXISTS
subqueries:
IF EXISTS
(
SELECT *
FROM sys.dm_hadr_availability_replica_states ars
INNER JOIN sys.databases dbs
ON ars.replica_id = dbs.replica_id
WHERE dbs.name = @DatabaseName AND ars.role = 2
) AND
EXISTS
(
SELECT *
FROM sys.availability_replicas
WHERE secondary_role_allow_connections_desc = 'ALL'
)
SET @HadrRole = 3
Note: you could use a SET
statement thus:
SET @HadrRole =
CASE
WHEN EXISTS
(
SELECT *
FROM sys.dm_hadr_availability_replica_states ars
INNER JOIN sys.databases dbs
ON ars.replica_id = dbs.replica_id
WHERE dbs.name = @DatabaseName AND ars.role = 2
)
AND EXISTS
(
SELECT *
FROM sys.availability_replicas
WHERE secondary_role_allow_connections_desc = 'ALL'
)
THEN 3
ELSE @HadrRole
END
answered Jan 28, 2014 at 20:44
Bogdan SahleanBogdan Sahlean
19.2k3 gold badges42 silver badges57 bronze badges
I used this to identify if the High Availability database on each server in a cluster was primary, secondary, read-only secondary. I’m going to use this to modify my SQL Agent jobs so they will run on the correct server in the cluster (read only secondary or primary depending on the job. Thanks for the replies! I hope this helps others.
USE [msdb]
GO
/****** Object: UserDefinedFunction [dbo].[RG_fn_HA_isPrimaryReplica_isSecondayReadable] Script Date: 1/27/2014 4:31:39 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF object_id(N'RG_fn_HA_isPrimaryReplica_isSecondayReadable', 'FN') IS NOT NULL
DROP FUNCTION RG_fn_HA_isPrimaryReplica_isSecondayReadable
GO
CREATE FUNCTION [dbo].[RG_fn_HA_isPrimaryReplica_isSecondayReadable] (@DatabaseName SYSNAME)
RETURNS TINYINT
WITH EXECUTE AS CALLER
AS
/********************************************************************
File Name: RG_fn_HA_isPrimaryReplica_isSecondayReadable.sql
Applies to: SQL Server 2012
Purpose: To return either 0, 1, or 2 based on whether this
@DatabaseName is a primary or secondary replica.
Parameters: @DatabaseName - The name of the database to check.
Returns: 0 = Resolving
1 = Primary
2 = Secondary
3 = Readable Secondary
Author: Matthew Joyce
Version: 1.0.0 - 01/28/2014
********************************************************************/
BEGIN
DECLARE @HadrRole TINYINT
-- Return role status from sys.dm_hadr_availability_replica_states
IF (SELECT ars.role
FROM sys.dm_hadr_availability_replica_states ars
INNER JOIN sys.databases dbs
ON ars.replica_id = dbs.replica_id
WHERE dbs.name = @DatabaseName) = 1
SET @HadrRole = 1
ELSE
-- @DatabaseName exists but does not belong to an AG so return 1
-- IF @HadrRole IS NULL
--SET @HadrRole = 1
--ELSE
--Return 2 if secondary but not readable
IF (SELECT ars.role
FROM sys.dm_hadr_availability_replica_states ars
INNER JOIN sys.databases dbs
ON ars.replica_id = dbs.replica_id
WHERE dbs.name = @DatabaseName) = 2 AND (SELECT secondary_role_allow_connections_desc
FROM sys.availability_replicas
where replica_server_name =(select @@ServerName)) <>'ALL'
SET @HadrRole = 2
ELSE
IF (SELECT ars.role
FROM sys.dm_hadr_availability_replica_states ars
INNER JOIN sys.databases dbs
ON ars.replica_id = dbs.replica_id
WHERE dbs.name = @DatabaseName) = 2 AND (SELECT secondary_role_allow_connections_desc
FROM sys.availability_replicas
where replica_server_name =(select @@ServerName)) ='ALL'
SET @HadrRole = 3
RETURN @HadrRole;
END;
GO
answered Jan 29, 2014 at 12:08
If you get error Msg 512 that reads “Subquery returned more than 1 value…” in SQL Server, it’s because you’re using a subquery that returns more than one value in a scenario where this is not allowed.
Example of Error
Suppose we have the following two tables:
SELECT * FROM Dogs;
SELECT * FROM Cats;
Result:
+---------+-----------+ | DogId | DogName | |---------+-----------| | 1 | Fetch | | 2 | Fluffy | | 3 | Wag | | 4 | Fluffy | +---------+-----------+ +---------+-----------+ | CatId | CatName | |---------+-----------| | 1 | Meow | | 2 | Fluffy | | 3 | Scratch | +---------+-----------+
And we run the following query against those two tables:
SELECT * FROM Dogs
WHERE DogName = ( SELECT CatName FROM Cats );
Result:
Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
We can see that it resulted in error Msg 512.
This error message explicitly tells us that the “Subquery returned more than 1 value” and that “This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression”.
The solution to this will depend on what you’re trying to do in the query. Below are a couple of options for resolving this issue.
Solution 1
One way to deal with this is to use a different operator. What I mean is, use an operator other than =
, !=
, <
, <=
, >
, or >=
.
Here’s an example that uses the IN
operator:
SELECT * FROM Dogs
WHERE DogName IN ( SELECT CatName FROM Cats );
Result:
+---------+-----------+ | DogId | DogName | |---------+-----------| | 2 | Fluffy | | 4 | Fluffy | +---------+-----------+
Solution 2
Another option is to keep the equals (=
) operator (or whichever operator is in the original query), but change the subquery.
Here’s an example of changing the subquery, while keeping the equals operator:
SELECT * FROM Dogs
WHERE DogName = ( SELECT CatName FROM Cats WHERE CatId = 2 );
Result:
+---------+-----------+ | DogId | DogName | |---------+-----------| | 2 | Fluffy | | 4 | Fluffy | +---------+-----------+
In this case the subquery returned one value only, and the equals operator was fine with that.
Solution 3
Note that the above subqueries only return one column. If the subqueries returned multiple columns, we’d need to change the outer query so that it uses the EXISTS
operator.
Example:
SELECT * FROM Dogs d
WHERE EXISTS ( SELECT * FROM Cats c WHERE c.CatName = d.DogName );
Result:
+---------+-----------+ | DogId | DogName | |---------+-----------| | 2 | Fluffy | | 4 | Fluffy | +---------+-----------+
If we didn’t change it to use the EXISTS
operator, then we’d probably get error message 116.
Table of Contents
Approved
The software to fix your PC is just a click away — download it now.
If you see error code 512 error server sql on your computer, you should check these suggested solutions. g.Error 512: The subquery returned more than one value compared to 1. This will not be accepted if the subquery follows = ,! Equals, <, <=,>,> = pro if the subquery is recommended as an expression.
g.
When I right click on my SQL Server Enterprise Manager and just select the restore command, I get the following error message:
Error 512: The subquery returned more than one value. This is invalid if the subquery follows = ,! = ,,> = Or simply, if a subquery is used with respect to an expression.
If you usually think of one of the benefits of an outer query, but some subqueries return more than one value in this case, this is an error prone type.
Approved
The ASR Pro repair tool is the solution for a Windows PC that’s running slowly, has registry issues, or is infected with malware. This powerful and easy-to-use tool can quickly diagnose and fix your PC, increasing performance, optimizing memory, and improving security in the process. Don’t suffer from a sluggish computer any longer — try ASR Pro today!
select * from table1 t1.where t1.id = (select t2.id on table2 t2 … where t2.id = t1.id)
This error occurs when the subquery returns more results than any single occurrence of t1.id.
But … it looks like the error often occurs in EM – after right clicking on the database, select “All Tasks” and then “Restore Database”. This is right?
p>
If you are not happy as a single person, you will not be happy in a relationship.
1 – You can get a profiler trace when you run this command. You must enable it to see the SQL or unused procedure causing this error. Then figure out what the subquery should be referring to and clean up any companies involved. This will force someone to modify the msdb tables, and then everything should work again.
2 – Use the entire “recovery database” from the T-SQL command to rely on GUI-Back-EM. I’ve learned a lot lately to “never trust my GUI”. SQL BOL examples to perform each restore this way (using T-SQL). You need to know under which backup on your hard drive this backup is located. By default, it is less than “C: Program SQL files microsoft Server MSSQL BACKUP” (replace C: with the drive where SQL Server was installed).
Run the profiler as suggested by go1 to see why the problem is occurring.
It looks like one of the processes in the table “Re “Back Up …” in the MSDB contains almost all problem entries or scanned images are corrupted. Have you had any problems with a backup that failed halfway? Rebuild the “Backing Up …” indexes in the MSDB as needed.
Would it be helpful to know which version of SQL Server are you still using?
Have you fixed a specific bug? I get this error too and move on. Please let me know if you find an answer.
And if EM defines @B, every second subquery gets the maximum restart date for the database “database_Name_here”. If the audience has multiple restores with exact date, time (second and millisecond), our own result is a combination of “backup_set_id” and no other value, so EM will run 512.Run error
person
in this query against all databases on the server, this method is rerunning this important error.
Seriousness
16
Message Text
The subquery returned more than one value. E But if the subquery is invalid and follows = ,! =, <, <= And>,> =, or if the subquery can be used as an expression.
Explanation
If a subquery of an expression returns more than one specific result,it violates the user’s relational rule for the outer request, andError 512 is raised. An example of a proverb subquery that returnsthe result follows:
1> select * in table_one where back button =2> (select sum (a) table_two3> w where = table_one.y)4> forward
An example related to a query that returns more than a result, andraises the following error 512:
1> use ads 22> select go1> author.au_id comes from authors where2> author.au_id means (select titleauthor.au_id3> by author name)4> forward
Message 512, 16, Level 1:Line 1:The subquery returned more than one value. It is illegalif the next subquery is,! =, <, <=>, that> = or whenthe subquery is used as an expression. Law
Action
for problem in example use “ in
” inlinked to location “ =
“as an example implementations:
1> Select author.au_id from marketers who2> author.au_id to (select titleauthor.au_id From3> title author)4> forward
au_id------------172-32-1176213-46-8915 . .899-46-2035998-72-3567(Affected 19 lines)
Additional Information
For more information, see the chapter Using Subqueries: Queries InOther Queries “in the user’s Transact-SQLInstructions.
Versions In Which This Error Occurs
The software to fix your PC is just a click away — download it now.
Hi everyone,
Can anyone plz help me to solve this issue.
In my SQL Server Enterprise Manager, when I right click and select the restore command, I get the following error message:
Error 512: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <=, >, >= or when the subquery is used as an expression.
I’m totally baffled what this means…
Thanx…and I appreciate whatever help I get.
Muneeb.
julee_lovely
SSC Journeyman
Points: 96
If the you are equating one value from the outer query but the subquery returns more than one value in that case this type of error occurs.
Phil Parkin
SSC Guru
Points: 246338
I too have seen this error, with queries like
select * from table1 t1 where t1.id = (select t2.id from table2 t2 … where t2.id = t1.id)
The error occurs when the subquery returns more than result for any single occurrence of t1.id.
But … it sounds as though you are getting the error within EM — after right-clicking on a database, selecting ‘All Tasks’ and then ‘Restore Database’. Is that correct?
If you haven’t even tried to resolve your issue, please don’t expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.
geh1
SSC Enthusiast
Points: 145
2 things to try:
1 — You can run a profiler trace while you perform this command. This should allow you to see the SQL or stored procedure that is causing the error. Then, determine what the subquery is accessing and clean up whatever tables are involved. This would require you to modify tables in msdb, but it should work.
2 — Use the «restore database» command from T-SQL instead of relying on the GUI in EM. I learned a long time ago to «never trust your GUI». You should find plenty of examples in SQL BOL to perform the restore in this way (using T-SQL). You will need to know where the backup exists at on disk. By default, it will be under «C:\Program Files\Microsoft SQL Server\MSSQL\BACKUP» (replace C: with whatever drive SQL Server was installed in).
Hope one of these helps!
Peter Tillotson
Hall of Fame
Points: 3325
Run the profiler as geh1 suggests to see the query that is causing the problem.
It sounds like one of your ‘Backup…’ system tables on database MSDB might have a problem record on it or the indexes are corrupt. Have you had any probems with backups failing half way through? Perhaps rebuild the indexes on the tables called ‘backup…’ in MSDB.
It would help if we knew what version of SQLServer you are running?
Regards
Peter
SQlLogic
SSCrazy Eights
Points: 9686
Did you solve this error ? I am getting this error too and i am working on it. please let me know if you found any solution please.
fcastilloa
SSC Enthusiast
Points: 117
This error is generated by enterprise manager.
When you click in restore, EM run this query
declare @b-2 int;
set @b-2 = (select backup_set_id
from msdb..restorehistory o
where o.restore_date = (select max(i.restore_date)
from msdb..restorehistory i
where i.destination_database_name = N'database_Name_here'));
select min(backup_set_id)
from msdb..backupset
where type = 'L'
and backup_set_id > @b-2
and database_name = (select database_name
from msdb..backupset
where backup_set_id = @b-2)
And when EM set @b-2, the second subquery obtain de maximun restore date of «database_Name_here» database. if you have several restores at the same date, hour (second and millisecond), the result of value it’s a set of «backup_set_id» and not an unique value, therefore, EM launch the error 512.
EM Run this query for all database in the server, for this, in several oportunities, EM launch this error.
Sorry for my english.
Greetings,
Fernando