Rayy
Rayy

Reputation: 1

SQL - Transfer Data to different table after INSERT

I am trying to transfer data I have recently inserted into a table to another table in the same database

The insert is working however when I tried to create the query for data transfer I have problems with incorrect syntax and I am unsure how to fix it. I am not even sure if I am using the correct query

I am quite new to this department so I would some help if possible

TLDR: I am trying to write a query that transfers any data I have inserted from one table to another every time

This is my query:

CREATE PROCEDURE [dbo].[sproc_tablename]
    INSERT INTO table1 (Name1)
        SELECT Name2
        FROM table2;
        WHERE tbl1_ID = tbl2_ID

Here's how it looks like

Upvotes: 0

Views: 65

Answers (2)

marc_s
marc_s

Reputation: 754993

You have two issues in your code:

CREATE PROCEDURE [dbo].[sproc_tablename]
AS            -- this was missing and is a *mandatory* keyword
    INSERT INTO table1 (Name1)
        SELECT Name2
        FROM table2;   -- <----- if you want the WHERE clause, *DO NOT* put a semicolon here!
        WHERE tbl1_ID = tbl2_ID

See the official Microsoft docs for more details on the syntax of CREATE PROCEDURE

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1270431

If you want to copy rows from one table to another, just use insert, but with no where clause (unless you want a subset of the records):

INSERT INTO table1 (Name1)
    SELECT Name2
    FROM table2;

If you want to update a column in the first table, then use update:

update t1
    set name = t2.name2
    from table1 t1 join
         table2 t2
         on t1.tbl1_ID = t2.tbl2_ID;

Upvotes: 1

Related Questions