Updating or inserting SQL Server destination table data based on conditions from source table data - sql

I have two SQL Server tables, one is my destination table (LocaleStringResource), the other one is the source table (TempResourceSunil).
Source table has the following columns: TempResourceSunil
[ID], [LanguageId], [ResourceName], [ResourceValue], [Burmese], [Unicode]
and the destination table's columns are LocaleStringResource
[Id], [LanguageId], [ResourceName], [ResourceValue]
I want to update the destination table [ResourceValue] based on [ResourceName] from the source file.
Example:
[ResourceName] = 'Account.AccountActivation'
means I want to check it have corresponding Burmese [ResourceValue] in LocaleStringResource table if it does not exist, I will take it from TempResourceSunil and Burmese column and insert it into LocaleStringResource with language id =2.
Same if [ResourceValue] for Unicode (language id = 3) does not exist for [ResourceName] = 'Account.AccountActivation' means I want to insert [ResourceValue] from TempResourceSunil with language id = 3.
Can any SQL expert help me?

The description you gave isn't really fleshed out however, you want to use a Case Statement. CASE STATEMENT INFO
A case statement can have multiple WHENs to cover multiple logic statements. You can even have one inside the other. I wouldn't really do that for this situation.
The example below is just a simple version.
If l.[ResourceValue] is null and l.[ResourceName] = 'Account.AccountActivation' then use the value of T.[Burmese] for column l.[ResourceValue]. ELSE means if no When within the case statement is true, then use this value.
Also be aware that if you are trying to use an INT value from the first table in a string column on the 2nd, you need to cast it as a varchar.
Test out your logic and case statements and see how you get on.
SELECT
l.[Id],
l.[LanguageId],
l.[ResourceName],
CASE WHEN l.[ResourceName] = 'Account.AccountActivation' and l.[ResourceValue] is null then T.[Burmese]
else l.[ResourceValue] end as [ResourceValue],
T.[ID],
T.[LanguageId],
T.[ResourceName],
T.[ResourceValue],
T.[Burmese],
T.[Unicode]
FROM LocaleStringResource as L
LEFT JOIN TempResourceSunil t on (t.ID = L.ID) and (t.[LanguageId] = l.[LanguageId])

Related

Insert Column with same value

I am running a query on the table "performance" and I want to insert a column with the same value for all the rows without using alter, update etc.
I wrote a case statement and it works but is there a more refined way?
here is a short query:
SELECT id, name, class,
CASE
WHEN id IS NOT NULL THEN 'Actuals'
ELSE 'Forecast'
END AS type
FROM performance
Basically I need all the values to be labeled "Actuals".
There are many other datasets for which I will use different labels and then append all of them
Just to be clear - don't need to update the table performance itself
use common table expression for your case.
It will add new column in your existing data and you may use this for your further process.
For your point it is not adding nor inserting anything in your existing db structure.
with CTE as (
SELECT id, name, class,
CASE WHEN id IS NOT NULL THEN 'Actuals' ELSE 'Forecast' END AS type
FROM table_performance
)
select * from CTE ----- It give you all the columns from [table] and add another column as you needed.
OR
You may create a view for same, if this condition is fixed.

cannot insert value NULL into column error shows wrong column name

I've added a new column(NewValue) to my table which holds an int and allows nulls. Now I want to update the column but my insert statement only attempts to update the first column in the table not the one I specified.
I basically start with a temp table that I put my initial data into and it has two columns like this:
create table #tempTable
(
OldValue int,
NewValue int
)
I then do an insert into that table and based on the information NewValue can be null.
Example data in #tempTable:
OldValue NewValue
-------- --------
34556 8765432
34557 7654321
34558 null
Once that's complete I planned to insert NewValue into the primary table like so:
insert into myPrimaryTable(NewValue)
select tt.NewValue from #tempTable tt
left join myPrimaryTable mpt on mpt.Id = tt.OldValue
where tt.NewValue is not null
I only want the NewValue to insert into rows in myPrimaryTable where the Id matches the OldValue. However when I try to execute this code I get the following error:
Cannot insert the value NULL into column 'myCode', table 'myPrimaryTable'; column does not allow nulls. INSERT fails.
But I'm not trying to insert into 'myCode', I specified 'NewValue' as the column but it doesn't seem to see it. I've checked NewValue and it is set to allow int and is set to allow null and it does exist on the right table in the right database. The column 'myCode' is actually the second column in the table. Could someone please point me in the right direction with this error?
Thanks in advance.
INSERT always creates new rows, it never modifies existing rows. If you skip specifying a value for a column in an INSERT and that column has no DEFAULT bound to it and is not identity, that column will be NULL in the new row--thus your error. I believe you might be looking for an UPDATE instead of an INSERT.
Here's a potential query that might work for you:
UPDATE mpt
SET
mpt.NewValue = tt.NewValue
FROM
myPrimaryTable mpt
INNER JOIN #tempTable tt
ON mpt.Id = tt.OldValue -- really?
WHERE
tt.NewValue IS NOT NULL;
Note that I changed it to an INNER JOIN. A LEFT JOIN is clearly incorrect since you are filtering #tempTable for only rows with values, and don't want to update mpt where there is no match to tt--so LEFT JOIN expresses the wrong logical join type.
I put "really?" as a comment on the ON clause since I was wondering if OldValue is really an Id. It probably is--you know your table best. It just raised a mild red flag in my mind to see an Id column being compared to a column that does not have Id in its name (so if it is correct, I would suggest OldId as a better column choice than OldValue).
Also, I recommend that you never name a column just Id again--column names should be the same in every table in the database. Also, when it comes join time you will be more likely to make mistakes when your columns from different tables can coincide. It is much better to follow the format of SomethingId in the Something table, instead of just Id. Correspondingly, the suggested old column name would be OldSomethingId.

Find columns with NULL values in Teradata

I would like to find the columns in a table that has a null value in it.
Is there a system table that have that information?
To find columns where "null" values are allowed try...
select *
from dbc.columns
where databasename = 'your_db_name'
and tablename = 'your_table_name'
and Nullable = 'Y'
then to identify the specific rows w/ null values, take the "ColumnName" from the previous result set and run queries to identify results... perhaps throw them in a volatile table if you want to take further action on them (update,delete).
-- for example you found out that column "foo" is nullable...
create volatile table isnull_foo_col
as
(
sel *
from your_table_name
where foo is null
) with data
on commit preserve rows;
If you have statistics collected on the column you can use the views found here for Teradata 12.0.03+ and Teradata 13.0.02+ to determine the number of records in the table that have NULL values.
In Teradata 14, if you use the SHOW STATISTICS with the VALUES clause you will get similar information generated by the views listed at the link above.
You can use the DBC.Columns data dictionary view to determine what columns in a particular table are nullable.

SQL: I need to take two fields I get as a result of a SELECT COUNT statement and populate a temp table with them

So I have a table which has a bunch of information and a bunch of records. But there will be one field in particular I care about, in this case #BegAttField# where only a subset of records have it populated. Many of them have the same value as one another as well.
What I need to do is get a count (minus 1) of all duplicates, then populate the first record in the bunch with that count value in a new field. I have another field I call BegProd that will match #BegAttField# for each "first" record.
I'm just stuck as to how to make this happen. I may have been on the right path, but who knows. The SELECT statement gets me two fields and as many records as their are unique #BegAttField#'s. But once I have them, I haven't been able to work with them.
Here's my whole set of code, trying to use a temporary table and SELECT INTO to try and populate it. (Note: the fields with # around the names are variables for this 3rd party app)
CREATE TABLE #temp (AttCount int, BegProd varchar(255))
SELECT COUNT(d.[#BegAttField#])-1 AS AttCount, d.[#BegAttField#] AS BegProd
INTO [#temp] FROM [Document] d
WHERE d.[#BegAttField#] IS NOT NULL GROUP BY [#BegAttField#]
UPDATE [Document] d SET d.[#NumAttach#] =
SELECT t.[AttCount] FROM [#temp] t INNER JOIN [Document] d1
WHERE t.[BegProd] = d1.[#BegAttField#]
DROP TABLE #temp
Unfortunately I'm running this script through a 3rd party database application that uses SQL as its back-end. So the errors I get are simply: "There is already an object named '#temp' in the database. Incorrect syntax near the keyword 'WHERE'. "
Comment out the CREATE TABLE statement. The SELECT INTO creates that #temp table.

Updating Records in Table A based on Records in Table B

I have to write a statement which fills a table (customers) with synthetically generated values. There is an addtional constraint that I should only fill those attributes (columns) with a special property (i.e. formally do a projection on them and then operate on them exclusively). These properties are stored in a second table, attributes.
My first draft consists of the following two statements:
-- Get the attributes (columns) we are interested in only
SELECT attributeID from attributes
WHERE tableID = 'customers'
-- Iterate over each row of customers, filling only those attributes (columns)
-- obtained by the above SELECT statement
UPDATE customers
SET (use the records from above select statement...)
Now my problem is how to put them together. I know there is the possibility of appending a WHERE clause to the SET clause, but that would select rows, not columns, as I need. I also read about PIVOT, but so far only inside one single table, not two, as is the case here. I would be very thankful for any hint, since I have no idea how to do this.
is not it you're looking for?
SQL Update Multiple Fields FROM via a SELECT Statement
UPDATE
Table
SET
Table.col1 = other_table.col1,
Table.col2 = other_table.col2
FROM
Table
INNER JOIN
other_table
ON
Table.id = other_table.id
Standard SQL-92 requires a scalar subquery:
UPDATE customers
SET attributeID = (
SELECT A1.attributeID
FROM attributes AS A1
WHERE A1.tableID = 'customers'
);
However, UPDATE customers...WHERE A1.tableID = 'customers' "smells" like you may be mixing data with metadata.