Setting set of text values for each ID - sql

I am working in SQL server and have two tables in my database, I am attaching their sample screenshots below:
Table 1:table_1
And the second table is as shown in the image below:
Table 2:table_2
I am trying to assign all the Korean language values from table_1 which are in Action_Item_in_Korean column to each value in the Asset_No column so my output should look like as shown below:
Output:Output
Each Asset_No should repeat 8 times because there are 8 values in table_1 that need to be updated. , I know that simple update query is not enough to display the output as I need, searched alot but so far unable to design a solution for this.

You tagged "cross join" and that seems like it satisfies your goal. A simple example is:
select <columns you desire>
from dbo.[table 1] as t1 cross join dbo.[table 2] as t2
order by ...
;

Related

select from some table based on results from a different table

I have a small table tbl_a that is something like
id
fieldName
tableName
1
field1
tbl_1
2
field2
tbl_1
3
field3
tbl_2
and I want to be able to come up with a function or proc or something where I can specify the fieldId from tbl_a and then query the correct field and table from that. something like
select * from my_function(3)
should end up being equivalent to
select field3 from tbl_2
I've been looking into dynamic sql and user functions but can't seem to figure out how to feed the results of the query into another.
EDIT:
As #Larnu correctly surmised, there is a larger task hiding behind the one posed in the original question. The premise is this:
tblArchive stores the values of certain "static" fields (found in other tables) with a Date attached. If/when these fields are changed in their original table, then a record is inserted into tblArchive. More-or-less an audit table.
eg: in tbl_accounts, AdjustmentFactor field (fieldId=3) for accountId=1 changes from 1.0 to 0.5 on '2022-06-10'.
Insert into tblArchive (fieldId, accountId, date, value) values (3,1,'2022-06-10',0.5)
tblArchive was only created in 2019. I've been tasked with back-filling records from 2017 on. That is, to insert records that would have been inserted had tblArchive existed in 2017.
In order to backfill, I have to look into the real audit tables (for previous example this would be tblAccountsAudit for that particular fieldId).
The fields of interest and their respective tables are given in tblFields. tblFields would be tbl_a from the original question and for the example given we'd have something like
id
fieldName
tableName
3
AdjustmentFactor
tbl_accounts
Assume also that the design is what it is and I have no power to overhaul the design/structure of the database.
It sounds like you need something like this.
CREATE FUNCTION myfunction (
#key INT
)
RETURNS TABLE
AS
RETURN
SELECT
id,
fieldName,
tableName
FROM
tbl_a
WHERE
id = #key;
This will give return the table you are after through a function.

Add data from one table into another with same column names

I have found numerous examples here, on YouTube, and in general Google searches but I'm still hitting a wall. I have two databases with (I believe) identical tables, structure, etc.
db1.dbo.table has a lot more information than does db2.dbo.table. I want to copy SOME of the information from db1.dbo.table into the already-created db2.dbo.table (which has some existing values I would like to keep).
Here's an example:
SELECT * FROM table WHERE TYPE = '1'
If I run that against db1.dbo.table, it returns a value of 12 rows. When run against db2.dbo.table, it ruturns 2 rows. I want to KEEP those two rows, but then add the other 12 rows from db1.dbo.table.
If I use:
select * into db2.dbo.table from db1.dbo.table
I get the error that the table already exists.
If I try the following:
Use db1
go
insert into table
select *
from table
where type (this is one of my column names) = '1' (one of the appropriate values)
I receive "An explicit value for the identity column in table 'table' can only be specified when a column list is used and IDENTITY_INSERT is ON." In researching that, I've tried the following:
Set Identity_Insert table (the name of my table) ON
Go
Insert into db2.dbo.table(column 1,column2,etc.,)
select (here, I've tried * as well as the same column1,column2,etc., values as above)
From db1.dbo.table
I've still not hit on the correct combination. I'd say I'm still a novice at SQL, but I understand technology and I comprehend what is happening in the examples I read/attempt to edit and execute for my environment, I'm just not sure of how to properly troubleshoot. I will restate below what I want to accomplish.
I want to copy values returned from:
SELECT * FROM TABLE WHERE TYPE = '1' in db1 (returns 12 rows)
into db2 (where the same returns 2 rows, I want this to return the same 2, plus the 12 from the other db when I'm done).
Instead of SELECT INTO, try to INSERT INTO:
INSERT INTO
db2.dbo.table
(
col1,
col2,
col3,
etc.
)
SELECT
col1,
col2,
col3,
etc.
FROM
db1.dbo.table
WHERE
TYPE = '1'

SQL Command to copy data from 1 column in table and 1 column in another table into a new table?

I had to make a new table to get the Include statement working in Entity Framework since EF was looking for a table called be_PostTagbe_Posts. I was using EF Code First from DB. But now the question is about SQL. I added one row of data and now the include works. But what I am looking for is a SQL command that can copy data from 1 column in 1 table and 1 column in another into the new be_PostTagbe_Posts table. In the be_Posts table I need the data in PostRowID to go into be_Posts_PostRowID and PostTagId to go into be_PostTag_PostTagID. Both be_PostTag_PostTagID and be_Posts_PostRowID are in the new be_PostTagbe_Posts table. I am not very good with SQL so not sure how to do this.
Edit: Thanks for the answers. I tried 2 separate queries but only data was inserted into the the be_PostTag_PostTagID while be_PostTag_PostRowID remained null.
And I tried this query which returned The multi-part identifier "be_PostTag.PostID" could not be bound.
INSERT INTO be_PostTagbe_Posts(be_PostTag_PostTagID, be_Posts_PostRowID)
SELECT be_PostTag.PostTagID, be_Posts.PostRowID
WHERE be_PostTag.PostID = be_Posts.PostID
EDIT:
This only inserted half the data - even 2 inserts leave one column null
INSERT INTO be_PostTagbe_Posts (be_Posts_PostRowID)
SELECT PostRowID FROM be_Posts;
INSERT INTO be_PostTagbe_Posts (be_PostTag_PostTagID)
SELECT PostTagID FROM be_PostTag;
And yet management studio tells me the query executed successfully but one column is still null. Weird.
Here are screenshots of the tables:
SELECT PostTagID AS be_PostTag_PostTagID, PostRowID AS be_Posts_PostRowID
INTO be_PostTagbe_Posts
FROM be_PostTag
Inner JOIN be_Posts
ON be_PostTag.PostID=be_Posts.PostID
That command created the new table with the 2 columns populated.
If i understand you ,you want to Copy Table Z's Column A to Table X And Table Z's Column B to Table Y.
If it is so, According to your question it is not clear about Table Structure of TableX and TableY
Assuming TableX And TableY to single ColumnTable [Apart from IdentityColumn] our query will be
INSERT INTO TableX
SELECT ColumnA FROM TableZ
INSERT INTO TableY
SELECT ColumnB FROM TableZ
Rest put your Entire Structure of Table To Get More Help Because These query are on Assumptions
There's not enough information in your question to give you a working example, but this would be the general syntax for INSERTing into a different table using a query SELECTing from two other tables.
INSERT INTO destination_table(wanted_value_1, wanted_value_2)
SELECT table_1.source_field_1, table_2.source_field_1
WHERE table_1.matching_field = table_2.matching_field
There has to be some sort of relationship between the two tables for the WHERE clause to work in that statement. I'm guessing based the little information you provided that there is a PostRowID field somewhere in the table that contains the tags such that your data would look similar to this in the tag table:
PostRowID PostTagID
--------- ---------
1 1
1 2
1 3
1 4
2 1
2 2
3 3
4 4
It sounds like you should use two sql statements:
Insert into `be_PostTagbe_Posts` (`be_PostTag_PostTagID`)
select `PostTagID` from POSTTAGIDTABLE
and
Insert into `be_PostTagbe_Posts` (`be_Posts_PostRowID`)
select `PostRowID` from POSTTAGIDTABLE
unless the items have some sort of relationship, then if you have a select statement that will select the merged data in two columns you can just do
Insert into `be_PostTagbe_Posts` (`be_PostTag_PostTagID`,`be_Posts_PostRowID`)
(select statement that selects the two items)

How to select data and insert those data using single sql?

I want to select some data using simple sql and insert those data into another table. Both table are same. Data types and column names all are same. Simply those are temporary table of masters table. Using single sql I want to insert those data into another table and in the where condition I check E_ID=? checking part. My another problem is sometime there may be any matching rows in the table. In that time is it may be out sql exception? Another problem is it may be multiple matching rows. That means one E_ID may have multiple rows. As a example in my attachment_master and attachments_temp table has multiple rows for one single ID. How do I solve those problems? I have another problem. My master table data can insert temp table using following code. But I want to change only one column and others are same data. Because I want to change temp table status column.
insert into dates_temp_table SELECT * FROM master_dates_table where e_id=?;
In here all data insert into my dates_temp_table. But I want to add all column data and change only dates_temp_table status column as "Modified". How should I change this code?
You could try this:
insert into table1 ( col1, col2, col3,.... )
SELECT col1, col2, col3, ....
FROM table2 where (you can check any condition here on table1 or table2 or mixed)
For more info have a look here and this similar question
Hope it may help you.
EDit : If I understand your requirement properly then this may be a helpful solution for you:
insert into table1 ( col-1, col-2, col-3,...., col-n, <Your modification col name here> )
SELECT col-1, col-2, col-3,...., col-n, 'modified'
FROM table2 where table1.e_id=<your id value here>
As per your comment in above other answer:
"I send my E_ID. I don't want to matching and get. I send my E_ID and
if that ID available I insert those data into my temp table and change
temp table status as 'Modified' and otherwise don't do anything."
As according to your above statements, If given e_id is there it will copy all the columns values to your table1 and will place a value 'modified' in the 'status' column of your table1
For more info look here
You can use merge statement if I understand your requirement correctly.
Documentation
As I do not have your table structure below is based on assumption, see whether this cater your requirement. I am assuming that e_id is primary key or change as per your table design.
MERGE INTO dates_temp_table trgt
USING (SELECT * FROM master_dates_table WHERE e_id=100) src
ON (trgt.prm_key = src.prm_key)
WHEN NOT MATCHED
THEN
INSERT (trgt.col, trgt.col2, trgt.status)
VALUES (src.col, src.col2, 'Modified');
More information and examples here
insert into tablename( column1, column2, column3,column4 ) SELECT column1,
column2, column3,column4 from anothertablename where tablename.ID=anothertablename.ID
IF multiple values are there then it will return the last result..If not you have narrow your search..

SQL query select from table and group on other column

I'm phrasing the question title poorly as I'm not sure what to call what I'm trying to do but it really should be simple.
I've a link / join table with two ID columns. I want to run a check before saving new rows to the table.
The user can save attributes through a webpage but I need to check that the same combination doesn't exist before saving it. With one record it's easy as obviously you just check if that attributeId is already in the table, if it is don't allow them to save it again.
However, if the user chooses a combination of that attribute and another one then they should be allowed to save it.
Here's an image of what I mean:
So if a user now tried to save an attribute with ID of 1 it will stop them, but I need it to also stop them if they tried ID's of 1, 10 so long as both 1 and 10 had the same productAttributeId.
I'm confusing this in my explanation but I'm hoping the image will clarify what I need to do.
This should be simple so I presume I'm missing something.
If I understand the question properly, you want to prevent the combination of AttributeId and ProductAttributeId from being reused. If that's the case, simply make them a combined primary key, which is by nature UNIQUE.
If that's not feasible, create a stored procedure that runs a query against the join for instances of the AttributeId. If the query returns 0 instances, insert the row.
Here's some light code to present the idea (may need to be modified to work with your database):
SELECT COUNT(1) FROM MyJoinTable WHERE AttributeId = #RequestedID
IF ##ROWCOUNT = 0
BEGIN
INSERT INTO MyJoinTable ...
END
You can control your inserts via a stored procedure. My understanding is that
users can select a combination of Attributes, such as
just 1
1 and 10 together
1,4,5,10 (4 attributes)
These need to enter the table as a single "batch" against a (new?) productAttributeId
So if (1,10) was chosen, this needs to be blocked because 1-2 and 10-2 already exist.
What I suggest
The stored procedure should take the attributes as a single list, e.g. '1,2,3' (comma separated, no spaces, just integers)
You can then use a string splitting UDF or an inline XML trick (as shown below) to break it into rows of a derived table.
Test table
create table attrib (attributeid int, productattributeid int)
insert attrib select 1,1
insert attrib select 1,2
insert attrib select 10,2
Here I use a variable, but you can incorporate as a SP input param
declare #t nvarchar(max) set #t = '1,2,10'
select top(1)
t.productattributeid,
count(t.productattributeid) count_attrib,
count(*) over () count_input
from (select convert(xml,'<a>' + replace(#t,',','</a><a>') + '</a>') x) x
cross apply x.x.nodes('a') n(c)
cross apply (select n.c.value('.','int')) a(attributeid)
left join attrib t on t.attributeid = a.attributeid
group by t.productattributeid
order by countrows desc
Output
productattributeid count_attrib count_input
2 2 3
The 1st column gives you the productattributeid that has the most matches
The 2nd column gives you how many attributes were matched using the same productattributeid
The 3rd column is how many attributes exist in the input
If you compare the last 2 columns and the counts
match - you can use the productattributeid to attach to the product which has all these attributes
don't match - then you need to do an insert to create a new combination