Insert into using Variables - sql

I have the following SQL query:
Declare #Total_SysDown as int,
#Login_SysDown as int
Set #Total_SysDown = (SELECT SCHED_SYS_DOWN FROM AGT_SC AS S)
Set #Login_SysDown = (SELECT SYS_DOWN FROM AGT_AC AS A)
Insert Into dbo.DATA(DATE,ID,LNAME,FNAME,Total_SysDown,Login_SysDown)
Select C.DATE,C.ID,E.Last_Name,E.First_Name,#Total_SysDown #Login_SysDown
From dbo.AGT as C Inner Join dbo.EMP as E ON C.ID = E.ID
Group by C.ID,C.DATE,E.Last_Name,E.First_Name
This or just the variables with the Select statement gives me an error of Subquery returned than 1 value. From what I understand, this means that I should be inserting one record at a time, but I am unsure how to do this. Is there a while statement I should be putting in, or are my variables actually hindering me in the first place?

At least one of the queries:
(SELECT SCHED_SYS_DOWN FROM AGT_SC AS S)
(SELECT SYS_DOWN FROM AGT_AC AS A)
returns more than 1 row, so you cannot assign it to a scalar variable.
As a temporary solution you can do SELECT TOP 1 to make sure each query returns at most one row.

I don't think the problem is with your INSERT statement at all.
Your problem is in the SET Statements. The SELECT SCHED_SYS_DOWN FROM AGT_SC AS S statement or the other statement is returning more than one value.
When you use SET you are assigning ONE value to the variable. Your SELECT is returning multiple values. Change your query to return only one row.

You're receiving this error because your subqueries return more than one record:
Set #Total_SysDown = (SELECT SCHED_SYS_DOWN FROM AGT_SC AS S)
Set #Login_SysDown = (SELECT SYS_DOWN FROM AGT_AC AS A)
To use variables here, you will need to ensure that only one record is returned from the query, either by using a WHERE clause, TOP 1, or something else. I can't tell for sure by your example, but it sounds like you should be joining those tables to your SELECT query.
SELECT ...
FROM dbo.AGT agt
INNER JOIN AGT_SC sc
ON sc.<joining column> = <joining table>.<joining column>
INNER JOIN AGT_AC ac
ON ac.<joining column> = <joining table>.<joining column>

Related

Where to declare a SET in SQL?

I have been attempting to figure out where I can SET a variable in an SQLQuery. I have 2 different select statements that will have a different WHERE clause depending on the answer to an IF statement, but I would like to only have to run the query to make SET this variable once, and since I am already running the code to find this particular table, I'd like to do it in the first SELECT statement.
The variable I am trying to SET is called regType
SELECT S.subID, C.cKey
FROM Comp AS C
JOIN JData AS J ON J.pKey = C.primary
JOIN Sub AS S ON J.fKey = S.pKey
WHERE ( //This is where I need the variable// )
I want to create a variable because I have a second SELECT that uses the same WHERE clause with the same conditions on it.
Where in this can I SET a variable within the SELECT statement so that I can use it in my WHERE?
It makes no sense to "set" a variable in a where clause - maybe you mean in the SELECT?
SELECT
S.subID,
C.cKey,
#regType = ???
FROM Comp AS C
JOIN JData AS J ON J.pKey = C.primary
JOIN Sub AS S ON J.fKey = S.pKey
WHERE ( ... )
Note that the variable will not be accessible in your WHERE clause of that query since the WHERE clause is evaluated before the SELECT. You can either repeat the expression that you're using in the SET or set the variable before you execute the query.

Subquery returns more than one row and stops working

I have a table which has got a column. I have to fetch the values from the column and modify it in the view before comparing it with an externally supplied value.
For that I am using the following query:
SELECT COUNT(*)
FROM tblMaster WITH (NOLOCK)
WHERE (SELECT test
FROM
(SELECT RIGHT('00000000000000000' + RTRIM(CODE), 17) as test
FROM tblMaster ) t) = '00001231231231231'
Subquery returns modified values of the column extracted from the actual table in form of a column. So I am using the column returned out of the subquery. I don't know if I can use a subquery which returns a column on the left side of equality.
Subquery returns multiple values.
You don't need a subquery for this:
SELECT COUNT(*)
FROM tblMaster WITH (NOLOCK)
WHERE right('00000000000000000' + RTRIM(CODE), 17) = '00001231231231231';
You can simplify this. You don't need to add 0s to integers, SQL will trim them off when comparing. Also you don't need the subquery:
SELECT COUNT(*)
FROM tblMaster WITH (NOLOCK)
WHERE CODE = '1231231231231'

performing an update query with a select subquery returning either the same value for ALL of the records or ora-01427 error

I need to update a column in one table with the results from a select sub-query (and they should ultimately be different). But When I do this, I either get the exact same number for the hundreds of records, or I get the ORA-01427: single row sub-query returns more than one row query. error.
Can you please take a look and see what it is that I am overlooking? (I could just be overlooking something simple for all I know)
UPDATE WD_PRODUCT_CLASS
SET CURRENT_CASES = ( WITH STUFF_COUNT AS
(
SELECT sum(CURRENT_DETAIL.COMBINED_QTY) AS TOTAL_CASES
FROM CURRENT_DETAIL, SKU_MAJORS, WD_PRODUCT_CLASS
WHERE CURRENT_DETAIL.LOC_ID =
&PARM_LOC_ID
AND CURRENT_DETAIL.INVEN_ID = SKU_MAJORS.INVEN_ID
AND WD_PRODUCT_CLASS.CATEGORY = SKU_MAJORS.CONT_DESC
GROUP BY WD_PRODUCT_CLASS.CATEGORY
)
(
SELECT SUM(Z.TOTAL_CASES) FROM STUFF_COUNT Z
)
);
Maybe you need someting like this:
UPDATE WD_PRODUCT_CLASS wpc
SET wpc.CURRENT_CASES = (
SELECT sum(cd.COMBINED_QTY)
FROM CURRENT_DETAIL cd join SKU_MAJORS sm ON cd.INVEN_ID = sm.INVEN_ID
WHERE cd.LOC_ID = &PARM_LOC_ID
AND sm.CONT_DESC = wpc.CATEGORY
)
WHERE 1=1; -- if you don't set a condition all the rows will be updated
Your query updates the table with the same values because you're using a not correlated subquery in the SET clause. This subquery don't depends on the parent query, so it's calculated only once.
I suppose you need a correlated subquery so I changed your update + removed some extra parts.

SQL IN() operator with condition inside

I've got table with few numbers inside (or even empty): #states table (value int)
And I need to make SELECT from another table with WHERE clause by definite column.
This column's values must match one of #states numbers or if #states is empty then accept all values (like there is no WHERE condition for this column).
So I tried something like this:
select *
from dbo.tbl_docs docs
where
docs.doc_state in(iif(exists(select 1 from #states), (select value from #states), docs.doc_state))
Unfortunately iif() can't return subquery resulting dataset. I tried different variations with iif() and CASE but it wasn't successful. How to make this condition?
select *
from dbo.tbl_docs docs
where
(
(select count(*) from #states) > 0
AND
docs.doc_state in(select value from #states)
)
OR
(
(select count(*) from #states)=0
AND 1=1
)
Wouldn't a left join do?
declare #statesCount int;
select #statesCount = count(1) from #states;
select
docs.*
from dbo.tbl_docs docs
left join #states s on docs.doc_state = s.value
where s.value is not null or #statesCount = 0;
In general, whenever your query contains sub-queries, you should stop for five minutes, and think hard about whether you really need a sub-query at all.
And if you've got a server capable of doing that, in many cases it might be better to preprocess the input parameters first, or perhaps use constructs such as MS SQL's with.
select *
from dbo.tbl_docs docs
where exists (select 1 from #states where value = doc_state)
or not exists (select 1 from #state)

Return a rowset and set a variable in an "IN" clause in SQL Server

I want use the SQL Server IN operator and also set a variable to a column value. Is this possible?
My code is like this:
DECLARE #SubkindId as tinyint;
SELECT NAME FROM SampleTable001 WHERE
Id in (SELECT Id, #SubkindId = Subkind FROM SampleTable002)
ORDER BY Name;
My issue is: I want to set the #SubkindId variable in the inner select statement.
Can It Be Done?
In SQL Server you can't SELECT a result set and SET variables in the same statement (though you can in MySQL). Sorry. But there may be another way to get what you want. Unfortunately, what you want is not completely clear.
Assuming you want to do a SELECT and at the same time return another value into a variable, you have to handle the issue that your query can return multiple rows, so in that case, which one would you want to return into #SubkindId?
Now, I may have misunderstood, and instead of trying to pull the column value into the variable, you instead want to pull only the row where the SubkindId matches the value already in the variable (though you didn't show assigning a value to it first, so this seems less likely).
Please confirm which is the case and answer the above questions, and I can help you more.
In the meantime, I'll try to give you answers for both scenarios.
First, let me mention that I recommend against using the IN() syntax with a subquery returning a list of IDs. It is poor practice in my opinion because it usually demonstrates that the person doesn't really know how to JOIN properly, and as soon as the query gets a little complicated, not only that person but even the best professional SQL Server query writer can get lost (... WHERE x IN (SELECT ... WHERE y IN (SELECT ... WHERE z NOT IN (...))) which soon leads to a serious case of what!?!?!?!. Just use JOINs, and if required, semi-joins (introduced with an EXISTS clause).
Query and Return a Value
If what you really wanted was to get access to the values that the SELECT statement found while doing its join, it might look something like this:
DECLARE #KindsAndSubkinds TABLE (
Name varchar(100),
SubkindId tinyint
);
INSERT #KindsAndSubkinds
SELECT
T1.Name,
T2.SubkindId
FROM
dbo.SampleTable001 T1
INNER JOIN dbo.SampleTable002 T2
ON T1.Id = T2.Id
SELECT DISTINCT Name
FROM #KindsAndSubkinds
ORDER BY Name;
-- Now you can something with the `SubkindId`s in the #KindsAndSubkinds table variable.
Just Query
If you really were just trying to query rather than return a value, this is what I would recommend:
DECLARE #SubkindId as tinyint;
SET #SubkindId = 5;
SELECT
T1.Name
FROM
dbo.SampleTable001 T1
INNER JOIN dbo.SampleTable002 T2
ON T1.Id = T2.Id
WHERE
T2.Subkind = #SubkindId
ORDER BY
T1.Name;
If there are multiple rows in SampleTable002 but you don't want them in the result set, then:
SELECT
T1.Name
FROM
dbo.SampleTable001 T1
WHERE
EXISTS (
-- This semi-join requires at least one row to exist
-- but doesn't increase the row count
SELECT *
FROM dbo.SampleTable002 T2
WHERE
T1.Id = T2.Id
AND T2.Subkind = #SubkindId
)
ORDER BY
T1.Name;
I hope this helps.
Do it like this:
DECLARE #SubkindId as tinyint
SELECT [NAME]
FROM SampleTable001
WHERE Id in (SELECT Id
from SampleTable002
WHERE Subkind=#SubkindId)
order by [Name]
or by using JOIN
DECLARE #SubkindId as tinyint
SELECT [NAME]
FROM SampleTable001 a
INNER JOIN SampleTable002 b
ON a.id = b.id
WHERE b.Subkind=#SubkindId
order by [Name]