Error when trying to update a row with a random value - sql-server

I am trying to update each row in a table with data from a random row from another table. Here is the SQL I am currently using:
SELECT Data, RowNumber FROM SampleData
SELECT FLOOR(ABS(CHECKSUM(NEWID())) / 2147483647.0 * 3 + 1) FROM Name
UPDATE Name SET Surname = (SELECT Data FROM SampleData WHERE RowNumber = FLOOR(ABS(CHECKSUM(NEWID())) / 2147483647.0 * 3 + 1))
And here are the results I'm getting:
Smith 1
Hunt 2
Jones 3
2
2
3
2
1
3
2
.... continues with a random number between 1 and 3 for each row in the Name table
Msg 512, Level 16, State 1, Line 9
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
So my question is why does the SELECT statement produce a single random number per row where the UPDATE sub-query seems to return multiple rows. I'm using SQL Server 2012 SP1 in case that makes a difference.

You are trying to update a field with a set of data, this leads to the described error.
Create a temporary mapping table and update name form the join between ID of name and "random" ID of SampleDate
SQLFiddle
SELECT ID,FLOOR(ABS(CHECKSUM(NEWID())) / 2147483647.0 * 3 + 1) as RN
Into #tmp
FROM Name
Update Name set SurName=Data
from #tmp
join SampleData sd on sd.RowNumber=#tmp.rn
where #tmp.ID=Name.ID
Select * from Name

Related

Can't perform an aggregate function on an expression containing an aggregate or a subquery

My table is created like this :
create table ##temp2(min_col1_value varchar (100))
create table ##temp1(max_col1_value varchar (100))
The table has values like this:
min_col1_value
-------------------
1
0
10
1
I'm trying to get the "frequency count of minimum length values" and expecting result as 3.
another example for maximum is :
max_col1_value
-------------------
1000
1234
10
1111
123
2345
I'm trying to get the "frequency count of maximum length values" and expecting result as 4.
When I'm running this query:
select count(min(len(convert(int,min_col1_value)))) from ##temp2 group
by min_col1_value
select count(max(len(convert(int,max_col1_value)))) from ##temp1 group by
max_col1_value
getting error as : Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
How to get the desired result?
You can't aggregate twice in the same SELECT statement and, even if you could, your min(len()) will return a single value: 2 since your minimum field length of #temp2 is 2. Counting that will just give you 1 because there is only 1 value to count.
You are wanting to get the count of how many fields have that minimum length so you'll need something like:
SELECT count(*)
FROM #temp2
WHERE len(min_col1_value) IN (SELECT min(len(min_col1_value)) FROM #temp1)
That WHERE clause says, only count values in #temp2 where the length is equal to the minimum length of all the values in #temp2. This should return 3 based on your sample data.
The same logic can be applied to either table for min or max.
This should get you your desired results:
SELECT COUNT(*)
FROM ##temp2
WHERE LEN(min_col1_value) =
(
SELECT MIN(LEN(min_col1_value))
FROM ##temp2
)
SELECT COUNT(*)
FROM ##temp1
WHERE LEN(max_col1_value) =
(
SELECT MAX(LEN(max_col1_value))
FROM ##temp1
)

SQL Server : update a table based on the result of another table with substring

I have 2 tables in my database, one of them contains a Description and a Code columns
Table_1
Description | Code
--------------------
123 street 23
321 street2 12
342 blabla 1
The other table has an Id column, and a description column
Table_2
Id | Description
------------------------------
41 street (textidontwant)
22 street2 (textidontwant)
33 blabla (textidontwant)
Basically, what I want to do is update the Code from Table 1 with the Id from table 2, however I need to use a substring to trim the description from Table 2 in order for the text to be matched with the description from Table 1.
I've already written the subquery, which is the following:
SELECT LEFT([Description], CHARINDEX('(', [Description]) - 1)) FROM Table_2
This right here trims the text inside the parenthesis just fine, but the problem is that I can't seem to be able to update Table_1 Code column with the Id from Table_2
I tried doing this:
UPDATE Table_1
SET Code = (SELECT T2.Id FROM Table_2 T2)
WHERE Table_1.[Description] = (SELECT LEFT([Description], CHARINDEX('(', [Description]) - 1)) FROM Table_2)
but I get this error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Any ideas?
Thanks for the help!
Don't use sub queries. Sql server allows you to use Joins in update statements.
UPDATE T1
SET Code = T2.Id
FROM Table_1 T1
INNER JOIN Table_2 T2
ON T1.[Description] = LEFT(T2.[Description], CHARINDEX('(', T2.[Description]) - 1)

Trying to Populate a Column with a Query

So I'm doing a data mining project for one of my classes. As part of it, I'm trying to apply Min Max Normalization to some of the data- which is the easy part. The hard part had been actually inserting the results of the queries into the table.
At first, I tried an INSERT INTO statement...
insert into dbo.CountsA([TotalCountMinMAx])
SELECT
1.00*(TotalCount-MinCount)/CountRange as TotalCountMinMax
FROM
(
SELECT
TotalCount,
MIN(TotalCount) OVER () AS MinCount,
MAX(TotalCount) OVER () - MIN(TotalCount) OVER () AS CountRange
FROM
dbo.CountsA
) X
The subquery itself works fine, but the moment I tried inserting the results into the table, it only inserted a number of null records. So instead of, say, updating ten entries in the TotalCountMinMAx column, it created ten additional records, and set all the columns to NULL.
After busting my head trying to figure that out, I tried using an UPDATE query instead.
update dbo.CountsA
set [TotalCountMinMAx]=(
SELECT
1.00*(TotalCount-MinCount)/CountRange as TotalCountMinMax
FROM
(
SELECT
TotalCount,
MIN(TotalCount) OVER () AS MinCount,
MAX(TotalCount) OVER () - MIN(TotalCount) OVER () AS CountRange
FROM
dbo.CountsA
) X)
This query failed to run entirely.
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
At this point, short of digging out my old SQL book and basically relearning SQL from scratch (I am very, very rusty), I'm out of ideas for making either of these codes work.
In case 1, when you insert, data will add row below old data. Example, if your table like:
ID | Col
1 2
2 4
After you insert just only Col column values: 3,4
Your table like this:
ID | Col
1 2
2 4
NULL 3
NULL 4
In case 2:
IF you use sub-query to insert like:
UPDATE Your_Table
SET Col = (<sub-query>)
sub-query must return a single value.
You can add where clause make sub-query return a single value, like this:
UPDATE Your_Table
SET Col = (SELECT ... FROM Your_Table) AS A
WHERE Col_ID = A.Col_ID
The problem is you are not correlating your sub-query that's the reason to get Sub-query retuned more than one row error.
Try using CTE to update which is easy and more readable.
;WITH cte
AS (SELECT 1.00 * ( TotalCount - MinCount ) / CountRange AS TotalCountMinMax_N,
TotalCountMinMax
FROM (SELECT TotalCount,
TotalCountMinMax,
Min(TotalCount)
OVER () AS MinCount,
Max(TotalCount)
OVER () - Min(TotalCount)
OVER () AS CountRange
FROM dbo.CountsA) X)
UPDATE cte
SET TotalCountMinMax = TotalCountMinMax_N

Getting "Subquery returned more than 1 value" error running update query

Please be gentle, I am trying to update the query in sql server but facing an error. Here is my two tables that are in same database and a query furnished below and my requirement is to update the column groupCode in table2 based on table 1 but I am facing the following error:
Error
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. The statement has been terminated.
Table 1
**Dept** **DeptCode** **GroupName** **GroupCode**
IT 32 Login-Els 1
IT 32 QC-Els 4
CT 20 Login-OUP 1
CT 20 XML-OUP 2
CT 20 QC-OUP 4
MECH 34 Login-CEN 1
MECH 34 XML-CEN 2
MECH 34 PAGINATION-CEN 3
MECH 34 QC-CEN 4
Table2
**Activity** **DeptCode** **Group**
Login-Els 32 NULL
QC-Els 32 NULL
Login-OUP 20 NULL
XML-OUP 20 NULL
QC-OUP 20 NULL
Login-CEN 34 NULL
XML-CEN 34 NULL
PAGINATION-CEN 34 NULL
QC-CEN 34 NULL
SQL
update db1..Activity set
Groupcode = (
select groupcode
from db1..Groups
where DeptCode=32
and Groupname = (
select activity
from db1..Activity
where DeptCode=32
)
)
The error message indicates that one or both of your subquery returned more than one row. That's not allowed as you're using the subqueries as operand of =. One possible way to fix the error is by adding TOP 1 to each of your subquery.
Another possible way to accomplish this kind of update task is by using UPDATE ... FROM ... JOIN syntax like so :
UPDATE Activity
SET Groupcode = G.groupcode
FROM Activity A
INNER JOIN Groups G
ON A.activity = G.Groupname
AND A.DeptCode = G.DeptCode
WHERE A.DeptCode = 32
error simply suggest you that you inner query return more than one value
hence sql get confused.so prevent multiple value my using top cluase
try this..
update db1..Activity set
Groupcode =(select top 1 groupcode from db1..Groups where DeptCode=32 and
Groupname =(select top 1 activity from db1..Activity where DeptCode=32))
You have to always update so that the inner select always returns one row. Your example doesn't really match with the example tables, but maybe this is what you want:
update
Table2
set
Group = (
select
GroupCode
from
table1
where
table1.DeptCode = table2.DeptCode and
table1.GroupName = table2.Activity
)
This part doesn't really make sense:
Groupname =(select activity from db1..Activity where DeptCode=32))
Because you're trying to update the table from itself, if that's really the case, then you can just use:
update table2 set GroupName = Activity
without using any inner selects.

How to update a column using group by in SQL

I have two tables and I want to update one row from GROUP BY data
This is my code:
2nd code:
UPDATE [TABLE].[dbo].[Movies]
SET [NumFrames] =
(SELECT COUNT(ImageURL) as "Count"
FROM [TABLE].[dbo].[Frames]
GROUP BY Movie_Id)
GO
1st code:
(SELECT COUNT(ImageURL) as "Count"
FROM [TABLE].[dbo].[Frames]
GROUP BY Movie_Id
1st code give me a row with numbers
Count
12
6
10
10
10
I want to insert it into Movies.NumFrames
2nd code give me an Error
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.
Please help
I'm sure it's simple
You need to use a WHERE-clause (GROUP BY is not necessary any more).
Otherwise your sub-query returns one row for each Movie_Id, so you have more than one row to use as source for your update.
UPDATE [TABLE].[dbo].[Movies]
SET [NumFrames] =
( SELECT COUNT(ImageURL) as "Count"
FROM [TABLE].[dbo].[Frames]
WHERE [TABLE].[dbo].[Frames].Movie_Id = [TABLE].[dbo].[Movies].Movie_Id
)

Resources