I'm new to SQL Server and was trying some SQL statements for my database.
I want to enable identity insert with the following statement:
SET IDENTITY_INSERT tableName ON
That works fine. After that I inserted an entry but if I close the script the changes are lost.
I also tried
EXEC sp_MSforeachtable #command1="PRINT '?'; SET IDENTITY_INSERT ? ON",
#whereand = ' AND EXISTS (SELECT 1 FROM sys.columns WHERE object_id = o.id AND is_identity = 1) and o.type = ''U'''
to enable identity insert for all tables, but that did not work either.
My expectation was that I run that script once and it will change the DB for all time but if I try to insert some entries with identity column, it doesn't insert the entry.
Related
I would like to know what would be a safe way to insert data over a linked/local server into a empty copy of the database(This database will have the same table structure) using "INSERT INTO SELECT"?
I will be getting data from the local server and this data will be inserted over a linked server or local server to an archive DB.
This process needs to happen through Dynamic SQL as I am writing a Generic script.
If you have a sample script that you can supply to me then I would appreciate it.
EXAMPLE
EXEC [server_name].[OI_OAF_Archive_20210218_20210222].[dbo].sp_executesql N'SET IDENTITY_INSERT [OI_OAF_Archive_20210218_20210222].dbo.[ENT_Entry] ON'
EXEC [server_name].[OI_OAF_Archive_20210218_20210222].[dbo].sp_executesql N'ALTER TABLE [OI_OAF_Archive_20210218_20210222].dbo.[ENT_Entry] NOCHECK CONSTRAINT ALL'
IF (EXISTS (SELECT * FROM [OI_OAF_Archive_20210218_20210222].INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'ENT_Entry'))
BEGIN
PRINT 'Inserting into the table ENT_Entry'
INSERT INTO [server_name].[OI_OAF_Archive_20210218_20210222].dbo.[ENT_Entry] (entryID,details,createdByID,createdDate,lastModifiedByID,lastModifiedDate,localityID,refNumber,entryDate,gps,reloadEscStep,createdAt,reloadOccurrenceChecklistRule) SELECT entryID,details,createdByID,createdDate,lastModifiedByID,lastModifiedDate,localityID,refNumber,entryDate,gps,reloadEscStep,createdAt,reloadOccurrenceChecklistRule FROM OPENQUERY([server_name], 'SELECT entryID,details,createdByID,createdDate,lastModifiedByID,lastModifiedDate,localityID,refNumber,entryDate,gps,reloadEscStep,createdAt,reloadOccurrenceChecklistRule FROM TMP_Archive_ENT_Entry_70CDC91A ');
END
EXEC [server_name].[OI_OAF_Archive_20210218_20210222].[dbo].sp_executesql N'SET IDENTITY_INSERT [OI_OAF_Archive_20210218_20210222].dbo.[ENT_Entry] OFF'
EXEC [server_name].[OI_OAF_Archive_20210218_20210222].[dbo].sp_executesql N'ALTER TABLE [OI_OAF_Archive_20210218_20210222].dbo.[ENT_Entry] CHECK CONSTRAINT ALL'
This Example is where I INSERT the DATA from The archive server, but I want to insert it from the local server into the archive server, would that be possible?
I tried searching but could not find exactly what I'm looking for. I'm new to SQl Server and involved into SQL Server to Oracle conversion, and it is manual conversion. All I have is SQL Server files.
I see two types of SQL Server triggers - FOR UPDATE and FOR INSERT. They look to me as before update and before insert triggers in Oracle. I'd like to confirm this please and if you can provide examples that would be great.
Also, what is the equivalent to master.dbo.sysprocesses in Oracle please? Is this v$session? I can get user from dual in Oracle. Is this what nt_username is in below code?
Here is typical code examples I need to convert to Oracle - is this before insert?
CREATE TRIGGER trigger_name ON dbo.table_name
FOR Insert AS
declare #InsertUser varchar(32)
BEGIN
SELECT #InsertUser = nt_username from master.dbo.sysprocesses where spid = ##spid
Update table_name
SET dCreateDate = GETDATE(), cCreateUser = #InsertUser
FROM table1 a ,table2 i WHERE a.tab_id = i.tab_id
END
GO
Update Trigger - before update?
CREATE TRIGGER trigger_name ON dbo.table_name
FOR UPDATE AS
declare #UpdateUser varchar(32)
if not update(CreateUser) and not update(CreateDate)
BEGIN
SELECT #UpdateUser = nt_username from master.dbo.sysprocesses where spid = ##spid
Update table_name
SET UpdateDate = GETDATE(), UpdateUser = #UpdateUser
FROM table1 a ,table2 i WHERE a.tab_id = i.tab_id
END
GO
Should I combine these two into if inserting... elsif updating in Oracle?
Thank you very much to all.
I want to migrate data from one database to another. I have written my sql statements to do so. However, the issue I a, facing is, I need to "use databasename GO" before executing the query (Can I fire use B and A at the same time to run my script?). Below is my query.
Use B GO
Use A GO
IF NOT EXISTS (select 1 FROM B.INFORMATION_SCHEMA.TABLES where table_schema = 'dbo' and table_name = 'Animal')
BEGIN
PRINT 'Table does not exist'
RETURN
END
GO
IF NOT EXISTS (select 1 FROM B.INFORMATION_SCHEMA.TABLES where table_schema = 'dbo' and table_name = 'Animal')
BEGIN
PRINT 'Table does not exist'
RETURN
END
GO
SET IDENTITY_INSERT B.[dbo].Animal ON GO
INSERT INTO B.[dbo].Animal
(Id, Name)
SELECT (Id, Name)
From A.dbo.Animal
GO
SET IDENTITY_INSERT B.[dbo].Animal OFF
GO
Would this work to move the data?
I have SQL Server 2008 R2. I have around 150 tables in a database and for each table I have recently created triggers. It is working fine in my local environment.
Now I want to deploy them on my live environment. The question is I want to deploy only the triggers.
I tried the Generate Script wizard but it is creating script with table schema along with triggers, NOT triggers only.
Is there anyway to generate all the triggers drop and create type script?
Forget the wizard. I think you have to get your hands dirty with code. Script below prints all triggers code and stores it into table. Just copy the script's print output or get it from #triggerFullText.
USE YourDatabaseName
GO
SET NOCOUNT ON;
CREATE TABLE #triggerFullText ([TriggerName] VARCHAR(500), [Text] VARCHAR(MAX))
CREATE TABLE #triggerLines ([Text] VARCHAR(MAX))
DECLARE #triggerName VARCHAR(500)
DECLARE #fullText VARCHAR(MAX)
SELECT #triggerName = MIN(name)
FROM sys.triggers
WHILE #triggerName IS NOT NULL
BEGIN
INSERT INTO #triggerLines
EXEC sp_helptext #triggerName
--sp_helptext gives us one row per trigger line
--here we join lines into one variable
SELECT #fullText = ISNULL(#fullText, '') + CHAR(10) + [TEXT]
FROM #triggerLines
--adding "GO" for ease of copy paste execution
SET #fullText = #fullText + CHAR(10) + 'GO' + CHAR(10)
PRINT #fullText
--accumulating result for future manipulations
INSERT INTO #triggerFullText([TriggerName], [Text])
VALUES(#triggerName, #fullText)
--iterating over next trigger
SELECT #triggerName = MIN(name)
FROM sys.triggers
WHERE name > #triggerName
SET #fullText = NULL
TRUNCATE TABLE #triggerLines
END
DROP TABLE #triggerFullText
DROP TABLE #triggerLines
Just in generate scripts wizard in the second step ("Set Scripting Options) press Advanced button=> Table/View Options=> Set Script Triggers to True.
check also this link or this. If you want only triggers just select one table to proceed the next step.
I'm trying to change the owner of a table:
sp_changeobjectowner 'OWNER.TABLENAME', 'dbo'
But when executing I get the error message:
Msg 15001, Level 16, State 1, Procedure sp_changeobjectowner, Line 62
Object 'OWNER.TABLENAME' does not exist or is not a valid object for
this operation.
The correct way to do this in SQL Server 2005 and up is to stop thinking about the prefix as an "owner." The sp_changeobjectowner procedure has been deprecated since SQL Server 2005, and you should instead be using schema DDL, e.g.:
ALTER SCHEMA dbo TRANSFER [current_owner].tablename;
To check the current "owner" (this may return multiple rows if you have more than one tablename in multiple schemas):
SELECT s.name
FROM sys.schemas AS s
INNER JOIN sys.tables AS t
ON s.[schema_id] = t.[schema_id]
WHERE t.name = N'tablename';
Also be sure that you spell the object correctly. In a case-sensitive collation, for example, TABLENAME and tablename are not the same object, and spelling it with InCorrEcT CaSe could also lead to this error.
Your statement is correct:
EXEC sp_changeobjectowner '<owner>.<tableName>', '<newOwner>'
If the error happend, try to check who is the current owner of the table:
EXEC sp_table_privileges '<tableName>'
To cover the case where a table exists within a constructed schema name like 'Common' (that is not related to a username), then it is the schema owner that needs to be changed.
alter authorization on schema::Common TO dbo;
That will change the objects within the schema to the specified owner 'dbo' and keep the table within 'Common'.
To list schema owners:
select db_name() as Db,
sch.name as SchemaName,
u.Name as Owner
from sys.schemas sch
join sys.sysusers u
on u.uid = sch.principal_id;
SELECT 'Exec sp_changeobjectowner ''<CURRENTOWNER>.' + name + ''', ''dbo'' ' FROM sys.objects WHERE type IN ('U','P','V','FN')
Apply Following Steps
(1) Run Following Query on Sql Prompt
(2) Copy The Result and Paste Again to New Sql Query and Again Execute
This is Change owner of your Tables, Views, Stored Procedures and Functions
If dropping the table is an option, you can drop and recreate under the desired user. Just specify dbo in the create script. For example:
USE [X]
GO
/****** Object: Table [dbo].[TableName] Script Date: 4/21/2014 1:26:37 PM ******/
CREATE TABLE [dbo].[TableName](
[Field1] [bigint] NOT NULL,
[Field2] [nvarchar](50) NOT NULL,
[Field3] [datetime] NOT NULL
) ON [PRIMARY]
GO
run the following query
EXEC sp_changeobjectowner 'set here object name', 'set here new owner'
go