How to get new column data from varchar column - sql

I got help to get select query to get the correct data, but how can I insert this into table.
Following
Select RIGHT(RTRIM(Template_name), 2) country
from TABLE
This gets for me following:
Example data:
Template_name Country
Party_package_US US
PARTY_Package_GB GB
Random_temp_DE DE
But the main question is how can I insert into table where template_name exists and add only the country initials to new column.
Link for earlier question where I got help: how to get info from VARCHAR column and create new column out of it
I figured that I could do subselect that inserts right form to new column
UPDATE #silverpop_header
SET MARKET_AREA = a.template_name
FROM #silverpop_header pop
join dw.f_CRM a
ON pop.template_name = a.TEMPLATE_NAME
left join (
select
RIGHT(RTRIM(Template_name), 2) country
from dw.f_CRM )
But I think I have done this wrong somehow

But the main question is how can I insert into table where template_name exists and add only the country initials to new column.
Please find the below script to perform the operation based on your comment mentioned above :
update silverpop_header set MARKET_AREA = (Select RIGHT(RTRIM(Template_name), 2) country from silverpop_header a where a.TEMPLATE_NAME = 'Party_package_US');
This will update the record for Party_package_US template. If you want to perform for all the templates then you have to write a simple cursor to read all template_name and execute the same update query for each template.
Update me if anything is required.
Find the cursor below which has been written for SQLServer.
DECLARE #TAMPLATENAME VARCHAR(100), #SQL VARCHAR(500), #quotes varchar(4)
DECLARE UPDATE_COUNTRIES CURSOR FOR SELECT TEMPLATE_NAME FROM silverpop_header
set #quotes = '''';
OPEN UPDATE_COUNTRIES
FETCH NEXT FROM UPDATE_COUNTRIES INTO #TAMPLATENAME
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = 'update silverpop_header set MARKET_AREA = (Select RIGHT(RTRIM(Template_name), 2) country from silverpop_header a where a.TEMPLATE_NAME = '+#quotes+#TAMPLATENAME+#quotes+' ) where TEMPLATE_NAME = '+#quotes+#TAMPLATENAME+#quotes
print(#SQL)
EXEC(#SQL)
FETCH NEXT FROM UPDATE_COUNTRIES INTO #TAMPLATENAME
END
CLOSE UPDATE_COUNTRIES
DEALLOCATE UPDATE_COUNTRIES

The final result that worked is following:
update #temp_table
set veerg2 = RIGHT(RTRIM(nimi), 3)
from #temp_table a
where a.nimi is not NULL ;
Just cuting out select on the SET part did the trick

Related

Enumerate the multiple rows in a multi-update Trigger

I have something like the table below:
CREATE TABLE updates (
id INT PRIMARY KEY IDENTITY (1, 1),
name VARCHAR (50) NOT NULL,
updated DATETIME
);
And I'm updating it like so:
INSERT INTO updates (name, updated)
VALUES
('fred', '2020-11-11),
('fred', '2020-11-11'),
...
('bert', '2020-11-11');
I need to write an after update Trigger and enumerate all the name(s) that were added and add each one to another table but can't work out how enumerate each one.
EDIT: - thanks to those who pointed me in the right direction, I know very little SQL.
What I need to do is something like this
foreach name in inserted
look it up in another table and
retrieve a count of the updates a 'name' has done
add 1 to the count
and update it back into the other table
I can't get to my laptop at the moment, but presumably I can do something like:
BEGIN
SET #count = (SELECT UCount from OTHERTAB WHERE name = ins.name)
SET #count = #count + 1
UPDATE OTHERTAB SET UCount = #count WHERE name = ins.name
SELECT ins.name
FROM inserted ins;
END
and that would work for each name in the update?
Obviously I'll have to read up on set based SQL processing.
Thanks all for the help and pointers.
Based on your edits you would do something like the following... set based is a mindset, so you don't need to compute the count in advance (in fact you can't). It's not clear whether you are counting in the same table or another table - but I'm sure you can work it out.
Points:
Use the Inserted table to determine what rows to update
Use a sub-query to calculate the new value if its a second table, taking into account the possibility of null
If you are really using the same table, then this should work
BEGIN
UPDATE OTHERTAB SET
UCount = COALESCE(UCount,0) + 1
WHERE [name] in (
SELECT I.[name]
FROM Inserted I
);
END;
If however you are using a second table then this should work:
BEGIN
UPDATE OTHERTAB SET
UCount = COALESCE((SELECT UCount+1 from OTHERTAB T2 WHERE T2.[name] = OTHERTAB.[name]),0)
WHERE [name] in (
SELECT I.[name]
FROM Inserted I
);
END;
Using inserted and set-based approach(no need for loop):
CREATE TRIGGER trg
ON updates
AFTER INSERT
AS
BEGIN
INSERT INTO tab2(name)
SELECT name
FROM inserted;
END

SQL Server UPDATE Column if Same CODE and DeptID Don't Exist

When I execute a Procedure I would like to UPDATE table1 and SET the new values for the CODE, NUMBER, and ADDRESS columns only if the same CODE and DeptID do not exist. If I change the CODE to an existing name in table1 it is OK as long as the DeptID is different.
Example:
Say I want to change Beta to Delta. That is fine because they have different DeptIDs. So I want to UPDATE everything, aka the third row in my example would now have the values (1, Delta, 'whateverNUMBER', 'whateverADDRESS')
But if I wanted to take that same third row Beta and change the CODE to Alpha I don't want to allow that and I don't want to SET the NUMBER or ADDRESS either because there is already a row with CODE Alpha and DeptID 1.
How would I be able to accomplish this?
Here is one of my attempts which does not work:
UPDATE dbo.table1
SET
CODE = #CODE
,NUMBER = #NUMBER
,ADDRESS = #ADDRESS
WHERE ID = #ID
AND NOT EXISTS
(
SELECT NAME FROM dbo.table1
WHERE NAME = #NAME
AND ID = #ID
)
This should work if you have the commas in the right place for syntax and specify the old code:
UPDATE dbo.table1
SET CODE = #CODE,
NUMBER = #NUMBER,
ADDRESS = #ADDRESS
WHERE ID = #ID AND
CODE = #OLDCODE AND
NOT EXISTS (SELECT 1
FROM dbo.table1
WHERE NAME = #NAME AND ID = #ID
);
The easiest would be to add a unique constraint for columns DeptId and Code.
This will prevent any duplicate insert as well as an update to already existing values.
The constraint will even prevent any changes performed directly against the table and not just within your update statement.

How to update 1 column only but to all rows with a calculation?

I want to update 1 column only for all rows in my table with the total calculation of :
The data of column multiply with random number between 0.9 to 1.2..
UPDATE TABLE
SET ABC = (SELECT ABC*(RAND()*((1.2-0.9)+0.9)) FROM TABLE)
Well idk how to write it in a proper T-SQL. I didn't get the expected result in SQL Server 2008 R2 with my query. Need your help guys to solve this things up.
Or you can give me another solution with using cursor.
Think you have a problem of parenthesis (for the rand "range"), than the way to write the query (if I understood well)
update table
set abc = abc * (RAND() * (1.2-0.9) + 0.9)
CAUTION
the "random" multiplicator will be the same for all the rows updated by this statement, as noticed by Damien_The_Unbeliever
SET NOCOUNT ON
DECLARE
#ABC_ID AS INT,
#RANDOM_GEN_NO AS VARCHAR(50),
#TEMP AS VARCHAR(50)
DECLARE ABC_CURSOR CURSOR FOR
SELECT #ABC_ID, RANDOM_GEN_NO FROM ABCTABLE FOR UPDATE OF RANDOM_GEN_NO
OPEN ABC_CURSOR
FETCH NEXT FROM ABC_CURSOR
INTO #EMP_ID, #RANDOM_GEN_NO
WHILE (##FETCH_STATUS = 0)
BEGIN
SELECT #TEMP = ABC*(RAND()*((1.2-0.9)+0.9))
UPDATE ABCTABLE SET ABC = #TEMP WHERE CURRENT OF ABC_CURSOR
FETCH NEXT FROM ABC_CURSOR
INTO #ABC_ID, #RANDOM_GEN_NO
END
CLOSE ABC_CURSOR
DEALLOCATE ABC_CURSOR
SET NOCOUNT OFF
OR IN Update Statement update ABCTable SET ABC = abc * yourcode
no need of select in update statement
UPDATE YourTABLE
SET ABC = ABC*(RAND()*((1.2-0.9)+0.9))
ok from your code block I see several basic syntax errors. The basic syntax of an update statement is
UPDATE [Tablename]
SET [Columnname] = (Value or Calculation or subquery)
WHERE (condition)
For more information check this
Try the below code:
UPDATE A
SET A.ABC = B.rand
from table A
inner join
(SELECT A.pkcolumn,A.ABC*(RAND()*((1.2-0.9)+0.9)) as rand FROM TABLE A)B
on A.pkcolumn = B.pkcolumn

sql issue with declare query

I've got a java application that I'm using to retrieve information from a table in sql.
The problem is that the tables change depending on the main application that is using them; there is a view that has all of the active information from the active table eg table_all which is fine, what i want to do is search for a particular number in table that was a part of the view
DECLARE #iss int, #act_tb char(1)
SET #iss = (select cust_nr from table_all where num = '123456789')
SET #act_tb = (select curr_table_active from pc_group where cust_nr = #iss)
select * from pc_grp_#iss_#act_tb
so what i would now want to do is update a field in pc_grp_#iss_#act_tbenter code here format is pc_grp_<#iss>_<#act_tb>.
is there any way i can do that as pc_grp_#iss_#act_tb is picked up as a table and not a variable table name.
Many thanks
i think you are looking for this-:
Declare #query as varchar(Max);
Set #query='Select * from select * from pc_grp_'+Cast(#iss as varchar)+'_'+Cast(#act_tb as varchar) ;
Exec(#query)

SQL error : Cannot insert duplicate id on inserting new data with existing one

I have a textbox on my modify page which holds the existing data from the database. This data are separate rows in the SQL Server table, but displayed as a single row separated by commas in the textbox.
For eg : table
keyid name
--------------
101 ss
105 hh
109 tt
In my webform it's displayed in a textbox like ss,hh,tt. There's a bridge table (Keysproducts) which holds the keyid and productid (product that's related to the keyid)
My issue here is:
On adding more entries along with existing ones in my textbox I get this error message saying duplicate values not be inserted and shows my existing id's. Below is my stored procedure for it.
I am checking if the keyname exists if not I insert the row, otherwise I update it. Please guide me if my approach is wrong.
create PROCEDURE [dbo].[modify]
(
#keyName nvarchar(256),
#productdbid uniqueidentifier
)
AS
Begin
declare
#productid uniqueidentifier,
#keyid uniqueidentifier,
#id uniqueidentifier;
declare #keydata table (keyid uniqueidentifier);
set #productid =(select ProductID from Products where ProductID = #productdbid );
Begin
if not exists(select keyname from keys where KeyName = #keyName)
begin
insert into Keys(KeyId, KeyName)
output inserted.KeyId into #keydata(keyid)
values (newid(), #keyName);
select #keyid = keyid from #keydata;
insert into KeysProducts(KeyId,productId)
values (#keyid, #productid);
end
else
begin
set #id = (select keyid from keys where KeyName = #keyName)
update keywords
set KeyId = #id, KeyName = #keyName
where KeyName= #keyName;
end
if not exists(select * from Keysproducts where ProductID = #productid and KeyId= #id)
begin
insert into Keysproducts(KeyId, ProductID)
values (#id, #productid);
end
else
begin
update Keysproducts
set KeyId = #id, productID = #productid;
end
end
end
end
Well, I think we'd need more info about how you're using this stored procedure. If your textbox originally has ss,hh,tt in it, and I change it to ss,hh,tt,zz for example, I'm assuming you run the procedure once for every value still? So you'd run it for ss, then again for hh, tt and zz individually?
Where do you get the productdbid parameter value from?
What constraints do you have on the table, and which one is violated (the PK, or some unique constraint)?
What exact error do you get?
I'd also like to point out that you have no WHERE clause on your last update, so you are trying to update every record in the table. If this Keysproduct table is the one you get the error for, this is why.
begin
update Keysproducts
set KeyId = #id, productID = #productid;
end