I have a unique issue. I have 2 tables that I must copy data into while changing the control group from 1 to 2. For every record in Controls, there is a record in Controls_Data to provide other information. Here's an example:
CREATE TABLE Controls (
PK_Controls INT IDENTITY,
PK_ControlGroup INT,
Description VARCHAR(50))
CREATE TABLE Controls_Data(
PK_Controls_Data INT IDENTITY,
PK_Controls INT,
PK_ControlGroup INT,
Data VARCHAR(50))
The first table I have no issue with. Copying the data can be accomplished simply by saying:
INSERT INTO Controls(PK_ControlGroup, Description)
Select 2, Description From Controls Where PK_Controls = 1
However copying the data from the second table becomes an issue. I now have to copy the data from Controls_Data while filling the PK_Controls column with the Primary keys of the new rows I created from the previous statement. I can't find a way to do this because the data being copied uses the old primary keys from the controls in group 1. Any solution would be greatly appreciated.
CREATE TABLE Controls (
PK_Controls INT IDENTITY,
PK_ControlGroup INT,
Description VARCHAR(50))
CREATE TABLE Controls_Data(
PK_Controls_Data INT IDENTITY,
PK_Controls INT,
PK_ControlGroup INT,
Data VARCHAR(50))
insert into Controls values(1, 'desc 1');
insert into Controls values(1, 'desc 2');
insert into Controls_Data (PK_Controls, PK_controlGroup )
select PK_Controls, PK_controlGroup
from
Controls where PK_ControlGroup = 1
--then insert 1 controls as 2 control group also into Controls_Data
insert into Controls (PK_controlGroup, [Description])
output
INSERTED.PK_Controls,
INSERTED.PK_ControlGroup
into Controls_Data(PK_Controls, PK_ControlGroup)
select 2 , [Description]
from
Controls where PK_ControlGroup = 1;
Related
I'm creating a table to store cars, and another table to store the time when the new car was added to the database, can someone please explain to me how to create the relationship to update time automatically when the car was created.
Create table Cars
(
CarID int Primary Key identity(1,1),
Make varchar(50),
Model varchar(50),
Colour varchar(59)
)
create Table TimeLogs
(
AddedOn SYSDATETIME(),
CarId int unique foreign key references Cars(CarId)
)
I would solve this by not using a second table for what should be a column in the Cars table. The table would be designed more appropriately like this.
Create table Cars
(
CarID int Primary Key identity(1,1),
Make varchar(50),
Model varchar(50),
Colour varchar(59),
AddedOn datetime default SYSDATETIME()
)
To automatically update one table whenever another table is updated, you need to use a TRIGGER.
You needs to use insert trigger for the same, as below
CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS
INSERT INTO yourDestinationTable
(col1, col2 , col3, user_id, user_name)
SELECT
'a' , default , null, user_id, user_name
FROM inserted
go
I have this data.
I want to duplicate data like a picture above with stored procedure.
First thing I do is copying two rows in the first table. How can I get 2 (two) 'iId' in the first table to create 2 (two) rows in the second table and put those 'iId' into 'iId_JTS-Rule_RulePricingGroup' like the picture above?
I think you can use OUTPUT clause with INSERT
CREATE TABLE #Table1(
ID int IDENTITY PRIMARY KEY,
Title varchar(10)
)
CREATE TABLE #Table2(
ID int,
Title varchar(10)
)
DECLARE #NewIDs TABLE(ID int)
INSERT #Table1(Title)
OUTPUT inserted.ID INTO #NewIDs(ID) -- save new IDs
VALUES ('A'),('B'),('C')
INSERT #Table2(ID,Title)
SELECT ID,Title
FROM #Table1
WHERE ID IN(SELECT ID FROM #NewIDs) -- use new IDs
DROP TABLE #Table1
DROP TABLE #Table2
Data is being migrated from Table A to Table B.
Table A has 2 columns - an identity column and a column Content defined as varbinary(max).
How can I validate that Table B has been loaded with correct data for Content column? Is T_SQL's EXCEPT operator good enough? Are there alternate methods?
Thanks
EXCEPT is the tool for this job. Note that unlike other SQL Server set operators, the order makes a difference. Here's one way to validate using EXCEPT:
-- sample data
DECLARE #table1 TABLE (id int identity, content varbinary(max));
DECLARE #table2 TABLE (id int identity, content varbinary(max));
INSERT #table1(content) VALUES (12), (15), (20);
INSERT #table2(content)
SELECT content
FROM #table1;
--solution
(
SELECT id, content FROM #table1
EXCEPT
SELECT id, content FROM #table2
)
UNION ALL
(
SELECT id, content FROM #table2
EXCEPT
SELECT id, content FROM #table1
);
I have a SQL Server table with the schema
varchar type,
varchar id,
int date,
varchar(MAX) data
And I want to split the data column into its own table and give it a unique index that I would put in my existing table (altered to accept an int instead of varchar(max) for data)
How can I select all of the rows and insert the data column into one table, then take the newly created auto_incremented id and insert the rest of the columns into another table with the auto_incremented id as the new 4th column?
Move the table to new temp table with Identity column. from that table, first create your new data table, then again create your second table.
declare #OriginalTable (type varchar, id Varcher,date int, data varchar(MAX))
declare #TempTable (Ident int identity(1,1), type varchar, id archer,date int, data varchar(MAX))
insert into #TempTable (type, id, date, data) select * from # OriginalTable
-- Create the Split tables
select ident, type, id, date into #Table1 From #TempTable
select ident, data into #Table2 From #TempTable
I have a Code (int) in my table, the ID is set to identity. How can I set a default value for my code to be filled by the same value az ID? I mean Identity.
You could use an after insert trigger:
create table TestTable (id int identity, col1 int)
go
create trigger TestTrigger on TestTable after insert
as begin
update TestTable
set col1 = id
where col1 is null
and id in (select id from inserted)
end
go
Test code:
insert TestTable default values
insert TestTable (col1) values (666)
insert TestTable default values
select * from TestTable
In general, I try to stay clear of triggers. In the long run using a stored procedure for insert is much more maintainable:
create procedure dbo.InsertTestRow(
#col1 int)
as
insert TestTable (col1) values (#col1)
if #col1 is null
begin
update TestTable
set col1 = id
where id = SCOPE_IDENTITY()
end
If it always has the same value - why don't you just drop that field. Otherwise it can be maintained with triggers (BEFORE INSERT one).
I'm looking for something in the
default value! If it is null it should
be filled with the same value as id
but if it is provided with some value,
it should keep that value
You could solve the issue by using coalesce in your queries instead.
create table T (ID int identity, ID2 int)
insert into T values (default)
insert into T values (null)
insert into T values (78)
select
ID,
coalesce(ID2, ID) as ID2
from T
Result
ID ID2
-- ---
1 1
2 2
3 78
Assuming your table's ID is an Identity column, you could consider using a constraint:
ALTER TABLE MyTable
ADD CONSTRAINT MyTableCodeDefault
DEFAULT IDENT_CURRENT('MyTable') FOR Code
This works for these use cases:
INSERT INTO MyTable DEFAULT VALUES
INSERT INTO MyTable ({columns NOT including 'Code'})
VALUES ({value list matching insert columns})
INSERT INTO MyTable (Code) VALUES (666)
INSERT INTO MyTable (Code) SELECT 8 UNION SELECT 13 UNION SELECT 21
But it does not work for bulk inserts:
INSERT INTO MyTable ({columns NOT including 'Code'})
SELECT {value list matching insert columns}
UNION
SELECT {value list matching insert columns}
UNION
SELECT {value list matching insert columns}
This restriction may seem onerous, but in my practical experience, it's rarely a problem. Most of the use cases I've encountered that need a default value involve user/UI 'convenience': don't force the user to pick a value if they don't want to.
OTOH, rarely do I encounter bulk insert situations where it's impractical to specify the value for the columns you're targeting.
You could use computed column, like this:
if object_id('TempTable') is not null drop table TempTable
create table TempTable (Id int identity(1,1), Code as Id)
insert into TempTable
default values
insert into TempTable
default values
insert into TempTable
default values
select * from TempTable
Of course if you have other columns, then you dont need default values:
if object_id('TempTable') is not null drop table TempTable
create table TempTable (Id int identity(1,1), Code as Id, SomethingElse int)
insert into TempTable (SomethingElse)
select 10 union all
select 11 union all
select 12
select * from TempTable
But, like zerkms said - why do you need two columns that are same?
If the field is an Identity field in SQL Server, the database engine will take care of its value. What we normally do is to read the record back (after inserting) to get to the generated Id.
EDIT: It sounds like you are trying to "override" the identity? If so, before you insert, run:
SET IDENTITY_INSERT [tableName] ON
You'll have to be careful not to insert a value that already exists. This can get tricky, though. So maybe consider removing the identity property altogether, and managing the default values yourself?