Add Column To one table on inserting value to another table - sql

I have two tables Branch_TB and Branch_City.
Branch_TB :
CREATE TABLE Branch_TB(
Branch_Id int NULL,
Branch_Name varchar(50) NULL
)
Whenever there is an entry for Branch_Name, I want to add that entry as column name in Branch_City.
Is there any way for this. I don't know how to do this and haven't try any solution.
Thanks in advance.

You can achieve that using AFTER INSERT TRIGGER.
CREATE TABLE Branch_TB(
Branch_Id int NULL,
Branch_Name varchar(50) NULL
)
go
--drop table BranchCity
create table BranchCity(abc varchar(20))
go
create TRIGGER dbo.AddCol
ON Branch_TB
AFTER INSERT AS
BEGIN
DECLARE #NewVal VARCHAR(20)
DECLARE #AlterSQL VARCHAR(100)
CREATE TABLE #New
(
VAL VARCHAR(20)
)
INSERT INTO #New
select Branch_Name from inserted
select #NewVal = Val from #New
SET #AlterSQL = 'ALTER TABLE BranchCity add ' + #NewVal + ' VARCHAR(20)'
exec(#AlterSQL)
END
go
insert into Branch_Tb
values(1, 'City1')
go
insert into Branch_Tb
values(2, 'City2')
But in my opinion, you should re-evaluate your database design.

you need to create trigger on insert row in Branch_TB table.
In trigger you need to add code for Add column in require table.
How to create Trigger in Sql ? check this.

I understand it like you want to duplicate inserted value in some other table in column name. If this is true then you can try with OUTPUT:
INSERT INTO Branch_TB( Branch_Id, Branch_Name )
OUTPUT 'someValue1', Inserted.Branch_Name, 'someValue2'
INTO Branch_City ( someCol1, Name, comeCol2 )
VALUES ( 1, 'some name' )

you can try this
create proc proc_branch (#b_name varchar(50)
as
begin
exec('alter table Branch_city add column '+ #b_name + ';');
end
go
create trigger tr_branch
on branch_TB
for insert
as
begin
declare #branch_name varchar(50);
set #branch_name=(select branch_name from inserted)
exec proc proc_branch
end

Related

In sql table insert two same values,if insert same value in 3rd time it not allow to insert that record

create table sample(id int primary key,name varchar(100))
insert into sample values(1,'a')
,(2,'a')
,(3,'d')
,(4,'b')
,(5,'b')
--insert into sample values(6,'a'),(7,'b')
this record is not allow to insert the table.it disply error
Easiest solution is to check the table if the value being inserted is already present in the table twice before the insert statement.
--Preparation
DECLARE #sample TABLE
(
id INT IDENTITY PRIMARY KEY --USE IDENTITY to auto increment your primary key
,name VARCHAR(100)
)
--Initial Values
INSERT INTO #sample
VALUES
('a')
,('a')
,('d')
,('b')
,('b')
DECLARE #name VARCHAR(100)
SET #name = 'a'
IF(SELECT COUNT(id) FROM #sample WHERE name = #name) <= 1
BEGIN
INSERT INTO #sample
VALUES (#name)
END
ELSE
BEGIN
SELECT 'Error: Name ''' + #name + ''' already exists twice. Only two same values are allowed in name field!'
END

Handling bulk insert on a table with multiple input sources in SQL

I am performing bulk insert on a table in sql server 2012, at the same time i am picking the last inserted row with max() function and inserting it into another table , how to perform this when my table is getting data from multiple sources because while performing insertion into secondary table there is time delay while insertions are still happening in primary table so next time max() will pick up last updated row and i will loose some rows which are not max() but still inserted into primary table meanwhile.
create table dbo.emp
(
id int primary key identity(1,1),
emp_id int,
name varchar(255),
address varchar(255)
)
create table dbo.empx
(
id int primary key,
emp_id int foreign key references dbo.emp(id),
)
declare #temp int ;
set #temp=1;
while #temp<1000
begin
insert into dbo.emp(emp_id,name,address)values (100+#temp,'Ename'+LTRIM(STR(#temp)),'123 Sample Address'+LTRIM(STR(#temp)));
set #temp=#temp+1;
insert into dbo.empx select max(dbo.emp.id),max(dbo.emp.emp_id) from dbo.emp
end
Use OUTPUT Clause...
CREATE TABLE #empx
(Id INT ,emp_id VARCHAR(50))
DECLARE #temp INT ;
SET #temp=1;
WHILE #temp<1000
BEGIN
INSERT INTO dbo.emp(emp_id,name,address)
OUTPUT INSERTED.Id,INSERTED.emp_id INTO #empx(Id,emp_id)
VALUES (100+#temp,'Ename'+LTRIM(STR(#temp)),'123 Sample Address'+LTRIM(STR(#temp)));
SET #temp=#temp+1;
END
INSERT INTO dbo.empx(Id,emp_id)
SELECT Id,emp_id FROM #empx
Or Use a trigger
CREATE TRIGGER EmpLog
ON dbo.emp
AFTER Insert
AS
BEGIN
SET NOCOUNT ON;
Insert into dbo.empx (id,emp_id) Select id,emp_id from inserted;
END
GO

Adding computed column in SQL

How to add computed column that calculates the sum of selected column.
this is what i've done but has an error..
ALTER TABLE dbo.tblEM_Reimbursement
ADD [Amount] AS (SELECT SUM(Total) FROM dbo.tblEM_ReimbursementEntry WHERE ReimbursementID = ReimbursementID)
it says
Msg 1046, Level 15, State 1, Line 2
Subqueries are not allowed in this context. Only scalar expressions are allowed.
Thanks in advance
You could use a user-defined function. Non tested code below.
CREATE FUNCTION dbo.Get_ReimbursementEntry (#ReimbursementID int)
RETURNS DECIMAL(10,2)
AS BEGIN
RETURN (SELECT SUM(Total) FROM dbo.tblEM_ReimbursementEntry WHERE ReimbursementID = ReimbursementID)
END
GO
ALTER TABLE dbo.tblEM_Reimbursement
ADD [Amount] AS (dbo.Get_ReimbursementEntry (ReimbursementID))
GO
but beware of the performance implications
You can use a Trigger. Trigger is a automated function written in PL/SQL whcih is called
after or before a particular event.
Read this tutorial for better understanding.
For SQL-Server read this and this.
Example:
CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)
INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);
Suppose you have another table:
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
This trigger is fired after an INSERT on the table. Let’s create the trigger as:
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]
FOR INSERT
AS
declare #empid int;
declare #empname varchar(100);
declare #empsal decimal(10,2);
declare #audit_action varchar(100);
select #empid=i.Emp_ID from inserted i;
select #empname=i.Emp_Name from inserted i;
select #empsal=i.Emp_Sal from inserted i;
set #audit_action='Inserted Record -- After Insert Trigger.';
insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(#empid,#empname,#empsal,#audit_action,getdate());
PRINT 'AFTER INSERT trigger fired.'
GO

SQL Server Stored Proc: Return ID of row deleted?

I have a stored proc where I am deleting a row from a table.
Is there a way to return the ID of the row deleted? I know there's a way to do it with inserting (SCOPE_IDENTITY()), but it doesn't seem to work for deletions.
The code:
BEGIN
declare #returnVal int
DELETE FROM table WHERE num = 1;
set #returnVal = /*HOW TO GET ID OF ROW DELETED?*/
END;
Yes you can. From here:-
CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
----Creating temp table to store ovalues of OUTPUT clause
DECLARE #TmpTable TABLE (ID INT, TEXTVal VARCHAR(100))
----Insert values in real table
INSERT TestTable (ID, TEXTVal)
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
VALUES (2,'SecondVal')
----Update the table and insert values in temp table using Output clause
DELETE
FROM TestTable
OUTPUT Deleted.ID, Deleted.TEXTVal INTO #TmpTable
WHERE ID IN (1,2)
----Check the values in the temp table and real table
----The values in both the tables will be same
SELECT * FROM #TmpTable
SELECT * FROM TestTable
----Clean up time
DROP TABLE TestTable
GO
You will have to run 2 commands: SELECT to retrieve ID and DELETE to actually perform deleteion.
BEGIN
declare #returnVal int
SELECT #returnVal = ID FROM table WHERE num = 1;
DELETE FROM table WHERE num = 1;
END;
Unless you delete based on ID - in that case you already know it.
Just insert an OUTPUT clause between the DELETE FROM and WHERE:
DECLARE #returnVal TABLE ([id] [int] NOT NULL)
DELETE FROM table
OUTPUT deleted.[id] INTO #returnVal
WHERE num = 1;
/* #returnVal contains the [id] values of all deleted rows. */
In a DELETE statement, you can access the data of deleted rows by the auto-created deleted table alias.

i am trying to execute the before insert trigger , but i m getting the sql errors

what i want to achieve is i have a table called orders.
i want to perform the before insert trigger on my orders table.i want to capture the
username of person performing INSERT into table.
one table called info which contain the user.
this is my code
create table orders
(
order_id int,
quantity int,
cost int,
total_cost int,
created_date datetime,
created_by varchar(20)
)
create trigger beforeInsertdata
before insert
on orders
for each row
declare
v_username varchar2(10);
begin
-- Find username of person performing INSERT into table
SELECT user INTO v_username
FROM info;
-- Update create_date field to current system date
:new.create_date := sysdate;
-- Update created_by field to the username of the person performing the INSERT
:new.created_by := v_username;
END;
--user information--
create table info
(
userid int ,
user_name varchar(10)
)
insert into info values(1,'vivek')
select * from info
Basically, triggers are classified into two main types:-
1)After Triggers (For Triggers)
2)Instead Of Triggers
and the syntax for trigger is
CREATE TRIGGER trigger_name ON table_name
[FOR|AFTER|INSTEAD OF] [INSERT|UPDATE|DELETE]
AS
//your code goes here
GO
NOTE : FOR keyword used for INSERT |UPDATE Command where as AFTER USED FOR DELETE Command.
It's hard to tell what you're really trying to do. I've modified your code sample so that it will work on SQL2K5 and made some assumptions about how you're wanting to use the connected user account.
CREATE TABLE orders (
order_id int,
quantity int,
cost int,
total_cost int,
created_date datetime,
created_by varchar(20)
);
CREATE TABLE info (
userid int,
user_name varchar(10)
);
INSERT INTO info
VALUES (1, 'vivek');
SELECT *
FROM info;
CREATE TRIGGER orders_InsteadOfInsert ON orders
INSTEAD OF INSERT AS BEGIN
SET NOCOUNT ON;
-- varchar(10) is to match your table, but probably should be larger
DECLARE #CurrentUser VarChar(10);
SELECT #CurrentUser = SYSTEM_USER;
IF (#CurrentUser NOT IN (SELECT user_name FROM info)) BEGIN
-- consider using an identity column for the key instead of this
INSERT INTO info (userid, user_name)
SELECT
ISNULL((SELECT MAX(userid) FROM info), 0) + 1,
#CurrentUser;
END;
INSERT INTO orders (order_id, quantity, cost, total_cost, created_date, created_by)
SELECT
INS.order_id,
INS.quantity,
INS.cost,
INS.total_cost,
GETDATE(),
#CurrentUser
FROM INSERTED INS;
END;