Update 1 table-col using 2 table-col from other table - sql

Is it possible to update 1 column/field of my table using 2 column/field from other table?
i tried this query :
UPDATE TEMP_Quantity
SET SS = (SELECT Qty1, Qty2 FROM Table_Quantity
WHERE Id = #IdHolder AND ProductId = 7)
WHERE Id = #IdHolder
And Sql said this error:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.`
SS = NVarchar (Because it can accept number or string base on the column that i will select)
can someone tell me the right way to do this? tia :)

Uhm... to answer your question, you can CONCAT both qty's
UPDATE t1
SET SS = CONCAT(t2.Qty1, t2.Qty2)
FROM TEMP_Quantity t1
INNER JOIN Table_Quantity t2 on t2.Id = t1.Id
WHERE t1.Id = #IdHolder
AND t2.ProductId = 7
But this just feels wrong.

Try this :
UPDATE TEMP_Quantity
SET SS = (SELECT CAST(Qty1 AS VARCHAR(10)) + CAST(Qty2 AS VARCHAR(10))
FROM Table_Quantity
WHERE Id = #IdHolder AND ProductId = 7)
WHERE Id = #IdHolder

You may use and examine the below script. I hope, it is usefull for you.
declare #qty1 int
declare #qty2 int
if object_id('tempdb..#dbDestination') is not null
drop table #dbDestination
create table #dbDestination(
Id int,
ss nvarchar(50)
)
if object_id('tempdb..#dbSource') is not null
drop table #dbSource
create table #dbSource(
Id int,
ProductId int,
qty1 int,
qty2 int
)
insert into #dbDestination(Id,ss) values (1,null),(2,null)
insert into #dbSource(Id,ProductId,qty1,qty2) values(1,7,10,3), (2,null,8,2)
UPDATE #dbDestination
SET SS = (
SELECT CAST(qty1 as nvarchar(50))+ cast(qty2 as nvarchar(50))
FROM #dbSource
WHERE Id = 1 AND ProductId = 7
)
WHERE Id = 1
select * from #dbDestination

Related

Filter via different dates in where clause

Here I've created a simple table using MS SQL
CREATE TABLE Students1 (
FirstName Nvarchar(100),
SecondName Nvarchar(100),
DOB Smalldatetime,
RegisterDate smalldatetime,
Archived int,
ArchivedDate Smalldatetime
);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('James','Bike',16/04/1900, 04/07/2017,0,Null);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Adam','Bike',16/04/1901,04/07/2017,0,Null);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Chris','Bike',16/04/1902,04/09/2017,1,getdate());
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Sam','Bike',16/04/1999,04/09/2017,1,getdate());
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Josh','Bike',16/04/1999,04/09/2017,1,getdate());
I want to do a simple select statement against this where I'm filtering on the either the RegisterDate or the ArchivedDate depending on how my local variables are set up.
For instance, i will have the following local variables set;
#FitlerRegisterDate
#FilterArchived
If either #FilterREgisterDate is set to 1 then the where clause will look at the RegisterDate column, but if the #FilterArchived is set to 1 then the where clause will look at the ArchivedColumn AND if they're both set to 1 then it should default to look at the RegisterDate
I've had a look at this for a while and cant see anything that stands out. If someone could point me in the right direction, that would be great.
Thanks.
You can use AND and OR clause to filter according to your variable values:
SELECT *
FROM dbo.Students1
WHERE ( #FilterArchived = 1
AND #FilterREgisterDate = 1
AND RegisterDate = #dateToFilter )
OR ( ( #FilterREgisterDate = 1
AND RegisterDate = #dateToFilter )
OR ( #FilterArchived = 1
AND ArchivedDate = #dateToFilter ) )
Something like this :
SELECT *
FROM Students1
WHERE #FilterREgisterDate = 1 AND RegisterDate = #RegisterDate
OR #FilterREgisterDate <> 1 AND #FilterArchived = 1 AND ArchivedDate = #ArchivedDate
;
?
select * from dbo.Students1 where (#FilterArchived=1 AND #FilterREgisterDate=1) and registerdate='04/07/2017'
UNION
select * from dbo.Students1 where (#FilterArchived!=1 AND #FilterREgisterDate=1) and registerdate='04/07/2017'
UNION
select * from dbo.Students1 where (#FilterArchived=1 AND #FilterREgisterDate!=1) and archived=1

Using ORDER BY command in an UPDATE SQL

I am looking at updating an item number column from a number of rows in a table (which match a particular Product ID & type) but I want to order the rows by numbers in a 'Seqnumber' column then the item number column start at 1 and count each row sequentially by 1.
Using the code below I have been able to select the product id and type I want and update the item number column with sequentially increasing values, however I don't know how I can order the required rows?
DECLARE #id nvarchar(6)
SET #id = 0
UPDATE Table1
SET #id = Table1.ItemNumber = #id + 1
WHERE Product = '5486' AND Table1.Type = 'C'
I know you can't use the ORDER BY command within the UPDATE command without using it as a sub-query. But I'm not sure how I should include this in the above code?
I think I need to incorporate the code below but not sure what the SELECT statement should be and when I try I can't get it to work?
DECALRE #id nvarchar(6)
SET #id = 0
UPDATE Table1
SET #id = TABLE1.ItemNumber = #id + 1
FROM (SELECT TOP (??)* FROM Table1
WHERE Product = '5486' AND Table1.Type ='C'
ORDER BY Table1.SeqNumber ASC
You should be able to build a CTE with the values you want from the table and just update the CTE
declare #Table1 table (Product varchar(4), [Type] varchar(1), SeqNumber int, ItemNumber int)
INSERT INTO #Table1 VALUES
('5486', 'C', 3, 0),
('5486', 'C', 2, 0);
with cte as (
select *,
ROW_NUMBER() OVER (ORDER BY SeqNumber) rn
from #Table1
where Product = '5486' and Type ='C'
)
Update cte
set ItemNumber = rn
This should work:
SET #id = 0;
UPDATE Table1
SET #id = Table1.ItemNumber = (#id := #id + 1)
WHERE Product = 5486 and Table1.Type = 'C'
ORDER BY Table1.seqnumber;
You cannot use ORDER BY with a JOIN, so you need to initialize the variable before the update.
UPDATE sales_data
SET ID = ID + 1
ORDER BY ID DESC;

How to copy records from table and insert into same table using stored procedure SQL Server

I have following table:
I want to copy only those records which are from version 0 and their student_id is never repeated in version 1, that means unchanged records. and I want to insert all copied records to same table with version 1. What will be stored procedure for this.
using group by and having max(version) = 0:
insert into student_name (student_id, student_name, version)
select student_id, max(student_name), 1
from student_name
group by student_id
having max(version) = 0
As a stored procedure, taking a parameter for version, that inserts records for students who do not have a record for that version: and outputs the rows that were inserted:
create procedure dbo.insert_new_version (#version int) as
begin;
set nocount, xact_abort on;
insert into student_name (student_id, student_name, version)
output inserted.*
select
student_id
, student_name = max(student_name)
, version = #version
from student_name
group by student_id
having max(version) < #version
end;
rextester demo: http://rextester.com/JSTNI40605
returns:
+-----------+------------+--------------+---------+
| record_id | student_id | student_name | version |
+-----------+------------+--------------+---------+
| 11 | 3 | ccc | 1 |
+-----------+------------+--------------+---------+
You can select the records by doing:
select t.*
from t
where t.version = 0 and
not exists (select 1
from t t2
where t2.student_id = t.student_id and t2.version = 1
);
The rest is just an insert.
I'd suggest using a while loop to go through the table and identify the items that you need to copy, then these values will be
evaluated and if they meet the criterion for re-inserting and then insert them.
Your code should look like the following. Add CREATE PROC part and Edit table names where applicable
(Caveat: I have written this on notepad so if you get a few errors, just try to fix them)
DECLARE #counter int = 0, #row_Count int = 0, #currentId int,
#currentName nvarchar(100), #version int, #current_Student_id int
SET #row_Count = (SELECT COUNT(record_Id) from yourTable)
WHILE #counter <= #row_Count
BEGIN
SET #currentId = (SELECT record_Id FROM (SELECT row_number() over (order by id)
AS RowNum, record_Id FROM yourTable) sub WHERE RowNum=#counter)
SET #currentName = (SELECT student_name FROM yourTable WHERE record_Id = #currentId)
SET #current_Student_id = (SELECT student_id FROM yourTable WHERE record_Id = #currentId)
SET #version = (SELECT version FROM yourTable WHERE record_Id = #currentId)
--USE IF to check if the current version is 0 and the student ID has not been inserted already
IF (SELECT COUNT(record_Id) FROM yourTable WHERE student_id = #current_Student_id AND version = 1) < 1
AND #version = 0
BEGIN
INSERT INTO yourTable (student_id, student_name, version)
VALUES
(
#current_Student_id,
#currentName,
1
)
END
SET #counter = #counter + 1;
END
You can select and insert like this
Insert INTO tableName select t1.student_Id, t1.student_name,1 from tablename t1
where t1.version = 0 and not exists
(select 1 from tablename t2 where t2.student_id = t.student_id and t2.version = 1);
You can try this by LEFT Join:
INSERT INTO tbl
SELECT T1.record_id,T1.student_Id,T1.student_name, 1
FROM tbl T1 LEFT JOIN tbl T2
ON T1.student_Id = T2.student_Id AND T2.version = 1
WHERE T1.version = 0 AND T2.record_id IS NULL

SQL Server : searching value doesn't have entry in table

I have a table which has the following values:
ID | Name
---------------
1 | Anavaras
2 | Lamurep
I need a query which outputs the value which doesn't have entry in the table.
For e.g:
If my where clause contains id in('1','2','3','4'), should produce output has
3 |
4 |
for the above entries in the table.
You would put this into a "derived table" and use left join or a similar construct:
select v.id
from (values(1), (2), (3), (4)) v(id) left join
t
on t.id = v.id
where t.id is null;
Something like this:
"SELECT id FROM table WHERE name IS NULL"
I'd assume?
First you need to split your in to a table. Sample split function is here:
CREATE FUNCTION [dbo].[split]
(
#str varchar(max),
#sep char
)
RETURNS
#ids TABLE
(
id varchar(20)
)
AS
BEGIN
declare #pos int,#id varchar(20)
while len(#str)>0
begin
select #pos = charindex(#sep,#str + #sep)
select #id = LEFT(#str,#pos),#str = SUBSTRING(#str,#pos+1,10000000)
insert #ids(id) values(#id)
end
RETURN
END
Then you can use this function.
select id from dbo.split('1,2,3,4,5',',') ids
left join myTable t on t.id=ids.id
where t.id is null
-- if table ID is varchar then '''1'',''2'',''3'''

SQL Server stored procedure WHERE clause

Need help with WHERE clause in this stored procedure.
How to write WHERE with this parameters and if any of these param contains specific value, then I need to get all values from that column ?
Sample if #post1 contains 1 then select values from that columns that are equals to 1.
But if #post1 contains 0 than select all values from that column. And that for all other parameters.
ALTER PROCEDURE [dbo].[spStavke]
#dat1 date,
#dat2 date,
#god int,
#post1 int,
#post2 int,
#post3 int
AS
BEGIN
SET NOCOUNT ON;
SELECT
[test1]
,[test2]
,[test3]
,[test3]
FROM
[PN].[dbo].[Stavke] AS stavke
LEFT JOIN
PN.dbo.Tip AS tip ON stavke.Vrsta = tip.id
LEFT JOIN
PN.dbo.Vrsta AS vrs ON stavke.Jedinica = vrs.id
END
SELECT
[test1]
,[test2]
,[test3]
,[test3]
FROM [PN].[dbo].[Stavke] as stavke
left join PN.dbo.Tip as tip on stavke.Vrsta=tip.id
left join PN.dbo.Vrsta as vrs on stavke.Jedinica = vrs.id
WHERE (#Post1 = 0 OR (#Post1 = 1 AND 1 IN( TEST1,TEST2,TEST3))
AND (#Post2 = 0 OR (#Post2 = 1 AND 1 IN( TEST1,TEST2,TEST3))