Extending tables in SQL - sql

How to add a column to the table:
create table table1 (id integer primary key, field1 text)
? The column would be field2 text and the value for existing rows in this column should be value.

For MySQL:
ALTER TABLE table1 ADD field2 text;
UPDATE table1 SET field2='value';

That would be the SQL syntax:
ALTER TABLE table_name ADD column_name datatype
In your case, you'd be looking at:
alter table table1 add field2 text
update table1 set field2 = 'value'

Related

TSQL How do I create a new table from two existing tables [duplicate]

This question already has answers here:
How to create table using select query in SQL Server?
(4 answers)
Closed 9 years ago.
I want to create a table from select query result in SQL Server, I tried
create table temp AS select.....
but I got an error
Incorrect syntax near the keyword 'AS'
Use following syntax to create new table from old table in SQL server 2008
Select * into new_table from old_table
use SELECT...INTO
The SELECT INTO statement creates a new table and populates it with
the result set of the SELECT statement. SELECT INTO can be used to
combine data from several tables or views into one table. It can also
be used to create a new table that contains data selected from a
linked server.
Example,
SELECT col1, col2 INTO #a -- <<== creates temporary table
FROM tablename
Inserting Rows by Using SELECT INTO
Standard Syntax,
SELECT col1, ....., col# -- <<== select as many columns as you want
INTO [New tableName]
FROM [Source Table Name]
Please be careful,
MSSQL: "SELECT * INTO NewTable FROM OldTable"
is not always the same as
MYSQL: "create table temp AS select.."
I think that there are occasions when this (in MSSQL)
does not guarantee that all the fields in the new table are of the same type as the old.
For example :
create table oldTable (field1 varchar(10), field2 integer, field3 float)
insert into oldTable (field1,field2,field3) values ('1', 1, 1)
select top 1 * into newTable from oldTable
does not always yield:
create table newTable (field1 varchar(10), field2 integer, field3 float)
but may be:
create table newTable (field1 varchar(10), field2 integer, field3 integer)
Please try:
SELECT * INTO NewTable FROM OldTable
Try using SELECT INTO....
SELECT ....
INTO TABLE_NAME(table you want to create)
FROM source_table
Select [Column Name] into [New Table] from [Source Table]

Changing the column from NULL to NOT NULL when some data is inserted

I have a column Col1 nvarchar(10) null
I have to write a check constraint or trigger (I think it's not possible with check constraint), that will change the Col1 from null to not null when and only when some data is entered into the field or, rather, it will deny the column to get a null value after some non-null value is entered into the field.
It's because of application that first checks if that field is null, and if it is then it adds some value to it. After that the field can not be changed back to null.
For now I have the following:
create trigger [TRG_Col1_NotNull] on my.Table
instead of update
as
begin
if exists (
select * from inserted as i
where i.Col1 is null
)
raiserror ('You can not change the value of Col1 to null', 16, 1)
rollback transaction
end
Is this the best (or even correct) way to do this or is there any better and easier solution for this (maybe check constraint somehow)?
OK! The update!
Application works like this:
It first save data to table in PK column, Col1, Col2, Col3 values 1, null, text, date. After that it checks if Col1 is null and reads the PK column and writes it's values to Col1. So I get the 1, 1, text, data.
This could do what you asked (I know: it's after UPDATE, so actually, you'll change values two times, but I will not use AFTER/INSTEAD: what if other values should be updated?).
CREATE TABLE TES1 (ID INT, COL1 VARCHAR(10));
INSERT INTO TES1 VALUES (1,'X');
INSERT INTO TES1 VALUES (2,NULL);
CREATE TRIGGER TRG1 ON TES1
AFTER UPDATE
AS
BEGIN
UPDATE A SET COL1=CASE WHEN d.COL1 IS NULL THEN i.COL1 ELSE d.COL1 END
FROM TES1 A
INNER JOIN DELETED d ON A.ID = d.ID
INNER JOIN INSERTED i ON A.ID = i.ID;
END
Sample data
UPDATE TES1 SET COL1 = NULL WHERE ID=1;
SELECT * FROM TES1;
UPDATE TES1 SET COL1 = 'A' WHERE ID=1;
SELECT * FROM TES1;
UPDATE TES1 SET COL1 = 'B' WHERE ID=2;
SELECT * FROM TES1;
UPDATE TES1 SET COL1 = 'C' WHERE ID=2;
SELECT * FROM TES1;
You can create a CHECK constraint that will work only for new values.
ALTER TABLE [dbo].[Test] WITH NOCHECK ADD CONSTRAINT [CK_Test] CHECK (([Col1] IS NOT NULL))
GO
ALTER TABLE [dbo].[Test] CHECK CONSTRAINT [CK_Test]
GO
WITH NOCHECK option means that constraint will be created successfully even if the table has NULL values.
But, after this constraint is created, an attempt to insert new NULL value or update existing value to NULL will fail.

How to compare column of two table and insert a value into new table based on comparison in stored procedure in SQL Server

I want to create a procedure which should check a column between two tables and insert a value into another table based on comparison.
Table 1:
create table table1
(
ID int not null primary key,
)
Table 2:
Create table table2
(
ItemID int not null primary key,
ID int FOREIGN KEY REFERENCES Orders(OrderID) ,
Descp Text
)
Table 3:
create table table3
(
ID int,
ItemCheck char
)
value of ID column of table 3 should be same as table1's ID column and
if ID column of table1 table exist in table2 then value ItemCheck column of table3 should be 'true' oterwise 'false'.
Please give me some ideas and let me know if you have any doubt. Thanks in advance.
Sounds like you want something like this?
TRUNCATE table3;
INSERT INTO table3 (ID, ItemCheck)
SELECT ID,
CASE WHEN EXISTS (SELECT 1 FROM table2 t2 WHERE ID = t.ID)
THEN 'T'
ELSE 'F'
END
FROM table1 t
Declare #col1 varchar(10)
Declare #col2 varchar(10)
SET #col1 = Select column1 from table1 where id =1
SET #col1 = Select column1 from table1 where id =2
IF(#col1 == #col2)
BEGIN
// insert statement goes here
END

Exchange column order of table after it is created

I have created a table with 4 columns. I need to change the structure of the table. I need to interchange the position of the 4th and 2nd columns permanently. Is this possible in Oracle?
Not possible. See this.
Oracle only allows columns to be added to the end of an existing
table.
So you must drop and recreate the tables.
You can run a script like this:
CREATE TABLE TMP_TBL as SELECT * FROM TBL_ORIG;
ALTER TABLE TBL_ORIG ADD COLUMN COL3;
DROP TABLE TBL_ORIG;
CREATE TABLE TBL_ORIG AS SELECT COL1, COL3, COL2 FROM TMP_TBL;
DROP TABLE TMP_TBL
You would need to consider indexes as well as storage concerns.
Why in the world is this necessary? Column order means nothing in SQL.
Swap of columns col1 and col2
It is assumed that col1 is int and col2 is varchar2(20)
-- drop all indexes and constraints concerning col1 and col2
alter table your_table add temp_col int; -- type of col1
update your_table set col1 = null, temp_col = col1;
alter table your_table modify col1 varchar2(20); -- type of col2
update your_table set col2 = null, col1 = col2;
alter table your_table modify col2 int; -- type of col1
update your_table set col2 = temp_col;
alter table your_table drop column temp_col;
alter table your_table rename column col1 to temp_col;
alter table your_table rename column col2 to col1;
alter table your_table rename column temp_col to col1;
-- recreate indexes and constraints
Simply rename table columns if they are the same datatype. If not then Alter - see Sean and Egor examples.
Rename:
http://docs.oracle.com/cd/E11882_01/server.112/e25494/tables006.htm#ADMIN11662
And on the interview they are looking for Sean's answer. Just FYI...

Informix - update SET column with results from a subselect

I have a table with a collection column. I want to do a subselect which returns several integers and put the result in that collection column, however I can't find a syntax to do it through SQL. I did it by writing an SQL procedure which does the same thing (put results of SELECT in SET variable and return variable), however I'm trying to do the same without functions. Can it be done?
First, I create a temporary table:
CREATE TEMP TABLE table1 (
id INTEGER
, col2 SET(INT NOT NULL)
)
Then I fill it with test data:
INSERT INTO table1 (id) VALUES (1);
INSERT INTO table1 (id) VALUES (2);
And now this works:
UPDATE table1 SET col2 = SET{1,2};
...but I'm trying to do this and it doesn't work:
UPDATE table1 SET col2 = (SELECT id FROM table1) WHERE id = 1;
It returns this error:
[Error Code: -9632, SQL State: IX000] Value does not match the type of column (col2).
Manipulating SET types in pure SQL is a pain.
Your UPDATE is trying to assign an INTEGER to a SET OF INTEGER, and the error says "you can't do that".
You should be able to do:
UPDATE table1
SET col2 = SET { (SELECT id FROM table1 WHERE id = 1) }
WHERE id = 1;
However, I'm not sure what the correct modification is to get more than one value into the set; the inner WHERE is not there idly.
You can achieve this by using MULTISET and ITEM keyword
the following example will work:
CREATE TEMP TABLE table1 (
id INTEGER
,col2 MULTISET(INT NOT NULL)
);
INSERT INTO table1 (id) VALUES (1);
INSERT INTO table1 (id) VALUES (2);
UPDATE table1 SET col2 = MULTISET{1,2};
UPDATE table1
SET col2 = MULTISET(SELECT ITEM id FROM table1)
WHERE id = 1;
Be aware of the differences between SET and MULTISET
select set{1,2,1,3,1} from systables where tabid=1;
returns SET{1,2,3}
select multiset{1,2,1,3,1} from systables where tabid=1;
returns MULTISET{1,2,1,3,1}