Append columns to a table by selecting columns from another table - sql

Alter Table table2 add ( select column1, column2, column3, column4 from table1 );
I need to append columns in an existing table, by selecting the columns of another table.
I get Error! Looking forward for a possible solution

First, to add four new columns to the table use the following syntax:
ALTER TABLE Table2
ADD column1 <datatype> <allow null>,
column2 <datatype> <allow null>,
column3 <datatype> <allow null>,
column4 <datatype> <allow null>
Where <datatype> is the type of data you'll be adding to the column and <allow null> is NULL if you want to allow null values is the column and NOT NULL if you do not want to allow null values in the column.
For example to add four columns of type nchar with a size of 10 that allow null values you would do the following:
ALTER TABLE Table2
ADD column1 [nchar](10) NULL,
column2 [nchar](10) NULL,
column3 [nchar](10) NULL,
column4 [nchar](10) NULL
Next, to insert your data from table1 into this table as brand new record you would use the following sql:
insert into table2 (column1, column2, column3, column4)
select column1, column2, column3, column4
from table1
Note: if any of the original columns in your table are set to NOT NULL and do not have have a default value this will fail and you will have to set values for those columns as well. You would do that by using a command similar to where you set a specific value for the column not allowing NULL values:
insert into table2 ( existingColumn, column1, column2, column3, column4)
select 'value to insert', column1, column2, column3, column4
from table1

Related

Is is possible to use a CTE combined with a UDT to delete data?

I have a stored procedure that takes in a UDT. I would like to sanitize this data before inserting into the database to prevent any duplicate data from getting inserted. (Primary Key is still allowing duplicate data just the PK is different).
So I am using shorthand with a cte to get remove all of the possible duplicate rows and then use the clean data to insert into my table
The problem is I am getting an error that "#UDT_MyTable is READONLY and cannot be modified". Is there someway around this without going the temp table route?
Create Procedure InsertIntoMyTable
(
#UDT_MyTable dbo.MyUDT readonly
)
as
Begin
declare #TodaysDate datetime = CURRENT_TIMESTAMP
begin transaction
;with cte as
(
Select Row_Number() Over
(
PARTITION BY
Column1,
Column2,
Column3,
Column4,
Column5,
Column6
)
as sequence from
#UDT_MyTable
Errors Here
**Delete from cte Where sequence > 1**
insert into my table(
Column1,
Column2,
Column3,
Column4,
Column5,
Column6,
DateCreated
)
select
Column1,
Column2,
Column3,
Column4,
Column5,
Column6,
#TodaysDate
from cte

Get columnnames as string sepparated by comma / list

i am doing some inserts with some of my tables and all fields but a few need to be inserted or updated. Like here.
Is there a quick way to get the columns of a table returned as a string so i can copy them into my sql query?
For example i have a table:
create table myTable1
(
column1 integer not null,
column2 integer not null ,
column3 integer not null,
column4 integer not null,
column5 integer not null,
...a lot more fields...
)
And later i want to insert something from another table myTable2 that has the same fields (dont question my ways and why i have two identical tables).
INSERT INTO myTable SELECT column1, column2, column3, column4, ...
FROM table_source
But the tables have so many fields it is cumbersome to write them donw manualy and it would be faster to have a string where i can just delete the column names i dont need. Is there a nice query that ouputs "column1, column2, column3, column4, ..." so i dont have to write that myself and can copy tha into my query?
Found the answer quickly.
SELECT table_catalog, string_agg(column_name, ', ')
FROM information_schema.columns
WHERE table_schema = 'mySchema'
AND table_name = 'myTable' GROUP BY 1;
This query does the trick for me.

INSERT INTO subtract 2 values

Is it possible for an INSERT query to subtract 2 values you have entered to create a 3rd value that can then be inserted into a table - if that makes sense...
e.g.
INSERT INTO table1 (column1, column2, column3)
VALUES ('50', '25', column1 - column2)
INSERT INTO table1 (column1, column2, column3)
(select ('50', '25', column1 - column2) from table1 where conditions)
This is a sample query! hope it helps!
Convoluted:
INSERT INTO table1 (column1,column2,column3)
select column1,column2,column1-column2
from
(select 50 as column1,
25 as column2
) t
Since you can't reference other columns from the same SELECT clause, you have to do it as a subquery. I've also switched to using int literals rather than strings, because I can't make subtraction make sense in my head otherwise.
You could also do it using a Table Value Constructor:
INSERT INTO table1 (column1,column2,column3)
select column1,column2,column1-column2
from
( VALUES (50, 25)
) AS t (column1, column2);
As indicated in my comment though, if the relationship should always hold, I'd build table1 as:
CREATE TABLE table1 (
column1 int not null,
column2 int not null,
column3 as column1 - column2
--More columns
)
Because that way, the column3 value is always correct.
You can create function that subtracts values and use this function in insert. This is the right way to do such things:
INSERT INTO table1 (column1, column2, column3)
(select ('50', '25', your_function() ) from table1 where conditions)
/
Using the "INSERT INTO" would do this:
INSERT INTO Table1Name (column1, column2, column3,)
(select 'X', 'Y', X - Y as Z)
Here is a link to SQL Authority with more examples of INSERT INTO
Another method would to be add a trigger to the table, where on insert of data, the third column would be updated with the difference of the first two columns.

Sql Query Create a new Table

Can anyone offered syntax for a sql query that takes an already created table and inserts some of the data into a new table with a new id(primary key)? So far I tried this
SELECT ((ID INT IDENTITY(1,1) PRIMARY KEY), column1, column2, column3)
INTO table_name
FROM table_name
I keep coming up with a syntax error.
SELECT column1, column2, column3
INTO table_name_new
FROM table_name_old
use like this
INSERT INTO newtable (column1, column2, column3)
SELECT (column1, column2, column3)
FROM table_name
INSERT INTO new_table
(Column1, Column2 . . . )
SELECT Column1, Column2 FROM old_table
Don't include the identity column (the primary key with the auto-generated numbers) in the insert list.
Just make it like below, Aa new id will be automatically created while inserting the record
insert into table1 (col1,col2,col3) select col1,col2,col3 from table2;
According to the documentation on MSDN, the IDENTITY property will transfer through with a SELECT INTO clause, but constraints will not. That means you can create a new table with an IDENTITY column if you include the original IDENTITY column from your source table, but the column in the new table won't be a primary key.
The sane way to do this is to use ALTER TABLE after the table is created, as #Kai has suggested.

Populating temporary table with result of independent Sql Query

I want to return a temporary table from stored procedure which populates with data retrieved from two independent sql query
Select column1,column2 FROM TABLE1 WHERE someCondition
Select column3,column4 FROM TABLE1 WHERE someOtherCondition
INSERT INTO Temp_table(column1,column2,column3,column4) values VALUE from those two table
Some of the result from table contains null as well.Also i am using some mathematical function like sum on some column as well
Thanks in advance
Try out with following code:
INSERT INTO Temp_table (column1, column2, column3, column4)
SELECT column1, column2, ISNULL(column3,0), ISNULL(column4,0) FROM TABLE1 WHERE someCondition
UNION ALL
SELECT ISNULL(column1,0), ISNULL(column2,0), column3, column4 FROM TABLE1 WHERE someOtherCondition
You want to do something like:
INSERT INTO Temp_table (column1, column2, column3, column4)
SELECT column1, column2, NULL AS column3, NULL AS column4 FROM TABLE1 WHERE someCondition
UNION
SELECT NULL AS column1, NULL AS column2, column3, column4 FROM TABLE1 WHERE someOtherCondition