Hi I have created two tables in a database. one is omconst another one is omstarline using the following sql:
CREATE TABLE "omconst" ([id] INTEGER NOT NULL UNIQUE,
[hr] INTEGER,
[name] TEXT,
[vmag] REAL,
PRIMARY KEY(id)
)
CREATE TABLE [omstarline] ([id] INTEGER NOT NULL UNIQUE,
[begin] INTEGER,
[end] INTEGER,
[name] TEXT,
PRIMARY KEY(id)
)
actually, I want to delete the record of table omconst
if omconst.hr != omstarline.begin
or
omconst.hr != omstarline.end.
How to use the SQL Query to do this? thanks in advance...
You can issue a delete statement using the not exists operator:
DELETE FROM omconst
WHERE NOT EXISTS (SELECT *
FROM omstarline
WHERE omconst.he IN (begin ,end)
Related
I have some SQL Server schema changes that I'm trying to convert to MySQL. I know about CREATE TABLE IF NOT EXISTS in MySQL. I don't think I can use that here.
What I want to do is create a table in MySQL, with an index, and then insert some values all as part of the "if not exists" predicate. This was what I came up with, though it doesn't seem to be working:
SET #actionRowCount = 0;
SELECT COUNT(*) INTO #actionRowCount
FROM information_schema.tables
WHERE table_name = 'Action'
LIMIT 1;
IF #actionRowCount = 0 THEN
CREATE TABLE Action
(
ActionNbr INT AUTO_INCREMENT,
Description NVARCHAR(256) NOT NULL,
CONSTRAINT PK_Action PRIMARY KEY(ActionNbr)
);
CREATE INDEX IX_Action_Description
ON Action(Description);
INSERT INTO Action
(Description)
VALUES
('Activate'),
('Deactivate'),
('Specified');
END IF
I can run it once, and it'll create the table, index, and values. If I run it a second time, I get an error: Table Action already exists. I would have thought that it wouldn't run at all if the table already exists.
I use this pattern a lot when bootstrapping a schema. How can I do this in MySQL?
In mysql compound statements can only be used within stored programs, which includes the if statement as well.
Therefore, one solution is to include your code within a stored procedure.
The other solution is to use the create table if not exists ... with the separate index creation included within the table definition and using insert ignore or insert ... select ... to avoidd inserting duplicate values.
Examples of options:
Option 1:
CREATE TABLE IF NOT EXISTS `Action` (
`ActionNbr` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`Description` VARCHAR(255) NOT NULL,
INDEX `IX_Action_Description` (`Description`)
) SELECT 'Activate' `Description`
UNION
SELECT 'Deactivate'
UNION
SELECT 'Specified';
Option 2:
DROP PROCEDURE IF EXISTS `sp_create_table_Action`;
DELIMITER //
CREATE PROCEDURE `sp_create_table_Action`()
BEGIN
IF NOT EXISTS(SELECT NULL
FROM `information_schema`.`TABLES` `ist`
WHERE `ist`.`table_schema` = DATABASE() AND
`ist`.`table_name` = 'Action') THEN
CREATE TABLE `Action` (
`ActionNbr` INT AUTO_INCREMENT,
`Description` NVARCHAR(255) NOT NULL,
CONSTRAINT `PK_Action` PRIMARY KEY (`ActionNbr`)
);
CREATE INDEX `IX_Action_Description`
ON `Action` (`Description`);
INSERT INTO `Action`
(`Description`)
VALUES
('Activate'),
('Deactivate'),
('Specified');
END IF;
END//
DELIMITER ;
CALL `sp_create_table_Action`;
I have the following script that I want to convert to SQL Server, but how?
MySQL:
CREATE TABLE mytable (
id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
uri VARBINARY(1000),
INDEX(uri(100))
);
How does this index looks like in MSSQL??
CREATE TABLE mytable (
id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1),
uri VARBINARY(1000),
--INDEX ???
);
sql-server doesn't have an inline index creation clause in its create table syntax. However, you can do it afterwards:
CREATE TABLE mytable (
id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1),
uri VARBINARY(1000),
);
CREATE INDEX my_table_uri_ind ON mytable(uri);
EDIT:
To address the comment below, you can use computed columns to gain the effect of indexing only part of your uri:
CREATE TABLE mytable (
id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1),
uri VARBINARY(1000),
uri100 AS SUBSTRING (uri, 1, 100)
);
CREATE INDEX my_table_uri_ind ON mytable(uri100);
Scenario:
I have a table which references two foreign keys, and for each unique combination of these foreign keys, has its own auto_increment column. I need to implement a Composite Key that will help identify the row as unique using combination of these three (one foreign keys and one auto_increment column, and one other column with non-unique values)
Table:
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (app_id, test_id,sr_no)
);
Of course, there has to be something wrong with my query, because of which the error thrown is:
ERROR 1075: Incorrect table definition; there can be only one auto
column and it must be defined as a key
What I am trying to achieve:
I have an Application Table (with app_id as its primary key), each Application has a set of Issues to be resolved, and each Application has multiple number of tests (so the test_id col)
The sr_no col should increment for unique app_id and test_id.
i.e. The data in table should look like:
The database engine is InnoDB.
I want to achieve this with as much simplicity as possible (i.e. avoid triggers/procedures if possible - which was suggested for similar cases on other Questions).
You can't have MySQL do this for you automatically for InnoDB tables - you would need to use a trigger or procedure, or user another DB engine such as MyISAM. Auto incrementing can only be done for a single primary key.
Something like the following should work
DELIMITER $$
CREATE TRIGGER xxx BEFORE INSERT ON issue_log
FOR EACH ROW BEGIN
SET NEW.sr_no = (
SELECT IFNULL(MAX(sr_no), 0) + 1
FROM issue_log
WHERE app_id = NEW.app_id
AND test_id = NEW.test_id
);
END $$
DELIMITER ;
You can do this with myISAM and BDB engines. InnoDB does not support this. Quote from MySQL 5.0 Reference Manual.
For MyISAM and BDB tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix.
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
I don't fully understand your increment requirement on the test_id column, but if you want an ~autoincrement sequence that restarts on every unique combination of (app_id, test_id), you can do an INSERT ... SELECT FROM the same table, like so:
mysql> INSERT INTO `issue_log` (`sr_no`, `app_id`, `test_id`, `issue_name`) SELECT
IFNULL(MAX(`sr_no`), 0) + 1 /* next sequence number */,
3 /* desired app_id */,
1 /* desired test_id */,
'Name of new row'
FROM `issue_log` /* specify the table name as well */
WHERE `app_id` = 3 AND `test_id` = 1 /* same values as in inserted columns */
This assumes a table definition with no declared AUTO_INCREMENT column. You're essentially emulating autoincrement behavior with the IFNULL(MAX()) + 1 clause, but the manual emulation works on arbitrary columns, unlike the built-in autoincrement.
Note that the INSERT ... SELECT being a single query ensures atomicity of the operation. InnoDB will gap-lock the appropriate index, and many concurrent processes can execute this kind of query while still producing non-conflicting sequences.
You can use a unique composite key for sr_no,app_id & test_id. You cannot use incremental in sr_no as this is not unique.
CREATE TABLE IF NOT EXISTS `issue_log` (
`sr_no` int(11) NOT NULL,
`app_id` int(11) NOT NULL,
`test_id` int(11) NOT NULL,
`issue_name` varchar(255) NOT NULL,
UNIQUE KEY `app_id` (`app_id`,`test_id`,`sr_no`)
) ENGINE=InnoDB ;
I have commented out unique constraint violation in sql fiddle to demonstrate (remove # in line 22 of schema and rebuild schema )
This is what I wanted
id tenant
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3
My current table definition is
CREATE TABLE `test_trigger` (
`id` BIGINT NOT NULL,
`tenant` varchar(255) NOT NULL,
PRIMARY KEY (`id`,`tenant`)
);
I created one table for storing the current id for each tenant.
CREATE TABLE `get_val` (
`tenant` varchar(255) NOT NULL,
`next_val` int NOT NULL,
PRIMARY KEY (`tenant`,`next_val`)
) ENGINE=InnoDB ;
Then I created this trigger which solve my problem
DELIMITER $$
CREATE TRIGGER trigger_name
BEFORE INSERT
ON test_trigger
FOR EACH ROW
BEGIN
UPDATE get_val SET next_val = next_val + 1 WHERE tenant = new.tenant;
set new.id = (select next_val from get_val where tenant=new.tenant);
END$$
DELIMITER ;
This approach will be thread safe also because any insertion for the same tenant will happen sequentially because of the update query in the trigger and for different tenants insertions will happen parallelly.
Just add key(sr_no) on auto-increment column:
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (app_id, test_id,sr_no),
key (`sr_no`)
);
Why don't you try to change the position of declare fields as primary key, since when you use "auto_increment" it has to be referenced as the first. Like in the following example
CREATE TABLE `issue_log` (
`sr_no` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`test_id` INT NOT NULL ,
`issue_name` VARCHAR(255) NOT NULL ,
primary key (sr_no,app_id, test_id)
);
I have a preexisting sqlserver table. Among other fields it has an identity column called as ID which is also a primary key and a RecordNumber column which is a required field. The int value in the RecordNumber column has to be unique. So before inserting a row, I get the max value of the ID column, add 1 to it and then inserting the row with the RecordNumber field = ID + 1. The problem is when two users try to save at the same time, they may get the same ID value and hence will save the same value in the RecordNumber field. Please let me know how to resolve this.
Thanks
The simplest and most efficient way to do this is to define that column as *auto increment *
refer
http://www.w3schools.com/sql/sql_autoincrement.asp
You can use the Transaction concept, using Commit and Rollback operations.
Very interesting link on MSDN : http://msdn.microsoft.com/en-gb/library/ms190295.aspx
Alternative #1 - Auto Increment a Field
CREATE TABLE SampleTable
(
P_Id int NOT NULL Identity(1,1),
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
Alternative #2 - SequentialID as Default Constraint
CREATE TABLE SampleTable
(
P_Id uniqueidentifier NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
ALTER TABLE [dbo].[SampleTable]
ADD CONSTRAINT [DF_SampleTable_P_Id]
DEFAULT newsequentialid() FOR [P_Id]
Alternative #3 - NewID as Default Constraint
CREATE TABLE SampleTable
(
P_Id Varchar(100) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
ALTER TABLE [dbo].[SampleTable]
ADD CONSTRAINT [DF_SampleTable_P_Id]
DEFAULT (newid()) FOR [P_Id]
Sample recommended Stored Proc should be used in case of Muti User Transaction
BEGIN TRY
SET NOCOUNT ON
SET XACT_ABORT ON
Begin TRAN
--Your Code
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
I have SQL CREATE statements for MySQL. They have KEY.
Example :
CREATE TABLE a (
a varchar(25) NOT NULL DEFAULT '',
b varchar(20) NOT NULL DEFAULT '',
KEY location (a)
);
What is the CREATE statement for this table in MSSQL ? The KEY keyword does cause problem.
CREATE TABLE database1.dbo.a (
a nvarchar(25),
b nvarchar(25),
)
GO
CREATE INDEX a_index
ON database1.dbo.a(a)
GO
...change db and schema names
if key is the column name, you could use square brackets to surround it..and then run the sql statement, like this:
[KEY]