Cross-database trigger in SQL Server - sql-server

I have two tables CrossDBTrigTest_1 and CrossDBTrigTest_2 on same SQL Server instance.
The databases both have a table called Employee.
I wrote the following trigger on the Employee table CrossDBTrigTest_1 db:
Create Trigger [dbo].[CrossDBInsert] on [dbo].[employee] after insert
AS
Begin
Set nocount on
Insert into CrossDBTrigTest_2.employee(FirstName, LastName, Date)
SELECT inserted.FirstName, inserted.LastName, getdate()
FROM inserted
End
but the Insert statement fails with message:
Msg 208, Level 16, State 1, Procedure CrossDBInsert, Line 5
Invalid object name 'CrossDBTrigTest_2.employee'.
How do I enable cross database triggers in situations like this??

Shouldn't
CrossDBTrigTest_2.employee(FirstName,LastName,Date)
be
CrossDBTrigTest_2.dbo.employee(FirstName,LastName,Date)
???

Use
CrossDBTrigTest_2..employee
as table name. Note two dots instead of one.

Related

There is already an object named 'name' in the database - stored procedure error - SQL Server

I have two tables called timeus and usdpay in my SQL Server database. These two tables get updated every week.
I did small transformation and combined these two tables and created a new table called fluslabor.
I created fluslabor using the stored procedure shown here, and it is working:
CREATE PROCEDURE [dbo].[sp_uslabor]
AS
BEGIN
SET NOCOUNT ON
IF OBJECT_ID(N'dbo.fluslabor', N'U') IS NOT NULL
TRUNCATE TABLE [dbo].[fluslabor];
SELECT ut.employee_code
,ut.employee_name
,ut.department_desc
,ut.location_desc
,ut.hour
,ut.projects_code
,ut.in_effective_time
,ut.out_effective_time
,ut.date
,ut.id
,p.rate
,(p.rate * ut.hour ) as Labour_Cost
INTO fluslabor
FROM timeus ut
LEFT JOIN usdpay p ON (TRIM(ut.id) = TRIM(p.id) AND ut.date = p.date)
WHERE ut.projects_code NOT LIKE '0%'
END
Today I got new data updated in my two tables timeus and usdpay.
When I execute my stored procedure, SQL Server is throwing this error:
Msg 2714, Level 16, State 6, Procedure SP_uslabor, Line 12 [Batch Start Line 38]
There is already an object named 'fluslabor' in the database.
I need to truncate my table every time and load the new data. I checked the similar post, they said to use drop table option. I don't want to drop the table, just want to truncate and execute the procedure
Can anyone advise what is the issue here please?
The problem here is that the table fluslabor already exists in the database. what you are trying above the insert is checking the object existence and then truncating the same
There are two possible approaches that you can try here.
Instead if the TRUNCATE do a DROP TABLE. But This will also remove the existing user permissions on the table if you have provided specific custom access to the table to any of the users
IF OBJECT_ID(N'dbo.fluslabor', N'U') IS NOT NULL DROP TABLE [dbo].[fluslabor];
The safest approach will be change the SELECT .. INTO statement and convert it into INSERT INTO like this
INSERT INTO fluslabor ( <List your Destination columns> ) SELECT <List your Source columns> FROM <Source Query>
the 2nd approach will have the records loaded along with keeping all the existing permissions
IF EXISTS (SELECT 1 FROM sys.objects WHERE type = 'P' AND name = 'your SP name')
BEGIN
DROP PROCEDURE "your SP name";
END
GO
CREATE PROCEDURE "your SP name"
AS
BEGIN
.
.
.
.
try this one I guess this will help you.

i have create a basic store procedure..when i m changing in this and execute it give me error that this name of SP already exit

This is my code
USE AccountSystemTraining
GO
CREATE PROCEDURE dbo.precetics
AS
SELECT * FROM Department where id=1
GO
error:
Msg 2714, Level 16, State 3, Procedure precetics, Line 4 There is
already an object named 'precetics' in the database.
If the procedure already exists and you need to change it then you may need to use ALTER instead of CREATE:
ALTER PROCEDURE dbo.precetics AS SELECT * FROM Department where id=1 GO
Note: From SQL Server 2016 you can do
CREATE OR ALTER PROCEDURE dbo.precetics AS SELECT * FROM Department where id=1 GO
which will always work without erroring regardless the procedure exists or not. In previous SQL server you can go around the issue by testing for existence first.

Migrate data from non Normalized database to a well Design database

I am migrating reads from a poorly design table to the newly Normalize one in sqlserver 2008.
My goal here is to get a count of total record in the Source table store in in a variable. The loop through each row and insert to the destination table. I have made numerous search on similar posts:
1: How do I insert a record from one table into another table? and Inserting into database by reading another
But was able to modify a code from SQL Examples
Now am get this error:
Msg 207, Level 16, State 1, Line 5
Invalid column name 'Num_Row_in_table
Code:
DECLARE #i INT
DECLARE #Num_Row_in_table int
SET #i=1
WHILE(#i <= Num_Row_in_table)
BEGIN
Insert into Destinationtable (FirstName,LastName,Photo,SN)
(
Select FirstName,LASTNAME,Photo,SN From MyDB.dbo.sourcetable
)
SET #i=#i+1
END
Forget the cursor; just do this:
Insert into Destinationtable (FirstName,LastName,Photo,SN)
Select FirstName,LASTNAME,Photo,SN From MyDB.dbo.sourcetable

Using stored procedures of another database

I have some procedures in database1 that are used to fill some tables using INSERT statements.
The tables I want to fill are in database2. How can I write a query with EXEC procedures in order to fill those tables?
I don't want to add stored procedures in the same database of the tables (database2)
This is one of the the stored procedures in db1
USE [database1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddSubject]
#SubjectCode nvarchar(20),
#Credits int,
#Hours int
AS
INSERT INTO [database2].[dbo].[Subject]
([Code]
,[Credits]
,[Hours])
VALUES
(#SubjectCode,
#Credits,
#Hours)
Return ##Identity
And here is where I execute the stored procedure:
EXEC #SubID = [database1].[dbo].[AddSubject] #SubjectCode='1234', #Credits=2, #Hours=50
And it gives me the error:
Msg 208, Level 16, State 1, Procedure AddSubject, Line 14
Invalid object name 'database2.dbo.Subject'.
You can refer to SQL Server tables with a four-part name:
server.database.schema.table
For a different database you only need the last three parts:
insert otherdb.dbo.yourtable
(col1, col2, ...)
values ('val1', 'val2', ...)
You can use this in a stored procedure to insert into a table in a different database.
Yes! you can acess the database2 into database1 for doing this both database should one server
If your scheema is dbo then you can access as below:-
Insert into database1..table_name (col1,col2)
select value1,value2
If your Scheema is other than dbo then :-
Insert into database1.Scheema_name.table_name (col1,col2)
select value1,value2

Inserting multiple values into a temporary table, SQL Server

I am using Microsoft SQL Server Management Studio, I am trying to run the following query to input values into a temporary table to use later:
CREATE TABLE #temptable
(colnumber varchar(15), dispcode varchar(10))
INSERT INTO #temptable (colnumber, dispcode)
VALUES
('col5', '811'),
('col6', '817'),
('col7', '823'),
('col8', '825');
When running I get the following error:
Msg 102, Level 15, State 1, Line 50
Incorrect syntax near ','.
Which points to the line "('col5', '811'),"
Could anyone help me identify the problem here?
For SQL Server version <2008 use this:
INSERT INTO #temptable (colnumber, dispcode)
SELECT 'col5', '811'
UNION ALL SELECT 'col6', '817'
UNION ALL SELECT 'col7', '823'
UNION ALL SELECT 'col8', '825'

Resources