How do i recreate a trigger in SQL Server? - sql-server

i use the statement drop trigger if exist TRIGGER in sqlite but sql server doesnt like the if statement. (i guess exist is the offending word). I do this right next to my create trigger statement because i want to drop older triggers with the same name so i can replace it with this new one.
How do i do this in SQL server?

in SQL Server Management Studio (and, I think in Query Analyzer) right-click the trigger in the explorer, and choose the Script-as option, choose 'Drop Trigger' in clipboard, and SSMS will create the T-SQL syntax for you to drop that trigger.
Sorry I haven't given you T-SQL you can copy and paste, but this way you'll know how to do it for next time.

You can check for the existence of a specific Trigger like so.
IF EXISTS
(
select name
from sys.objects
where type='TR' and name ='Trigger Name'
)
BEGIN
--Add your Trigger create code here
END

I find this to be a more compact SQL Server equivalent to MySQL's DROP TRIGGER IF EXISTS syntax:
IF OBJECT_ID('XXXX', 'TR') IS NOT NULL
DROP TRIGGER XXXX

I'd use something like:
IF objectproperty(object_id('dbo.xxx'), 'isTrigger') = 1
DROP PROCEDURE dbo.xxx
GO
CREATE TRIGGER dbo.xxx [etc]
replacing xxx with your trigger name (and dbo with the relevant schema, if necessary).
Alternatively, you could just use
ALTER TRIGGER dbo.xxx [etc]

Since version 2016 this syntax is also supported by Microsoft SQL Server:
DROP TRIGGER IF EXISTS trigger_name

Related

Issue with the IF EXISTS command

I am trying to get this command that is on auto run to have an automatic delete incase I have to re-run the application. I am using visual studio and sql server 2012.
Here is what I have. The Create table works but its the IF EXISTS that I am having trouble with.
IF EXISTS (DROP TABLE ST_BANLIST)
CREATE TABLE ST_BANLIST
(BAN VARCHAR (9).
CALL_ACTIVITY CHAR(1).
BAN_STATUS CHAR(1))
Thanks for any help
Your syntax was incorrect:
IF OBJECT_ID('dbo.ST_BANLIST', 'U') IS NOT NULL
DROP TABLE dbo.ST_BANLIST
SQL Server 2016 makes this a lot easier (what took so long Microsoft?):
DROP TABLE IF EXISTS dbo.ST_BANLIST
if exists(select * from sys.objects where name ='MytableName' and type='U')
Drop table dbo.MytableName

How do I make ALTER COLUMN idempotent?

I have a migration script with the following statement:
ALTER TABLE [Tasks] ALTER COLUMN [SortOrder] int NOT NULL
What will happen if I run that twice? Will it change anything the second time? MS SQL Management Studio just reports "Command(s) completed successfully", but with no details on whether they actually did anything.
If it's not already idempotent, how do I make it so?
I would say that second time, SQL Server checks metadata and do nothing because nothing has changed.
But if you don't like possibility of multiple execution you can add simple condition to your script:
CREATE TABLE Tasks(SortOrder VARCHAR(100));
IF NOT EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE [TABLE_NAME] = 'Tasks'
AND [COLUMN_NAME] = 'SortOrder'
AND IS_NULLABLE = 'NO'
AND DATA_TYPE = 'INT')
BEGIN
ALTER TABLE [Tasks] ALTER COLUMN [SortOrder] INT NOT NULL
END
SqlFiddleDemo
When you execute it the second time, the query gets executed but since the table is already altered, there is no effect. So it makes no effect on the table.
No change is there when the script executes twice.
Here is a good MSDN read about: Inside ALTER TABLE
Let's look at what SQL Server does internally when performing an ALTER
TABLE command. SQL Server can carry out an ALTER TABLE command in any
of three ways:
SQL Server might need to change only metadata.
SQL Server might need to examine all the existing data to make sure
it's compatible with the change but then change only metadata.
SQL Server might need to physically change every row.

SQL Server Trigger - Need to Alter

I need to alter a trigger in SQL Server. After I am doing, do I just execute the trigger similar to how I would do for a Stored Procedure?
ALTER TRIGGER
Yes, that is right, just use ALTER. If you right-click on your trigger in Object Explorer in SSMS and select Script Trigger as/ALTER To, you will see the ALTER statement created for your trigger.
ALTER TRIGGER triggerName
ON tableName
FOR INSERT -- or update & delete
AS
-- sql here
http://msdn.microsoft.com/en-us/library/ms176072.aspx
You don't "execute" a trigger. Triggers are "triggered" at certain points depending upon your definition of them.
For example an AFTER UPDATE trigger would run for all rows updated after you send an UPDATE command to the table on which the trigger is created.

How to add a new schema to sql server 2008?

How do you add a new schema to a database? I am creating a new table and would like to select my own schema from the properties list, but I don't know how to create it. I am using SQL Server Management 2008.
Use the CREATE SCHEMA syntax or, in SSMS, drill down through Databases -> YourDatabaseName -> Security -> Schemas. Right-click on the Schemas folder and select "New Schema..."
Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.
IF NOT EXISTS (SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = 'newSchemaName' )
BEGIN
EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END
I use something like this:
if schema_id('newSchema') is null
exec('create schema newSchema');
The advantage is if you have this code in a long sql-script you can always execute it with the other code, and its short.
Best way to add schema to your existing table: Right click on the specific table-->Design -->
Under the management studio Right sight see the Properties window and select the schema and click it, see the drop down list and select your schema. After the change the schema save it. Then will see it will chage your schema.
You can try this:
use database
go
declare #temp as int
select #temp = count(1) from sys.schemas where name = 'newSchema'
if #temp = 0
begin
exec ('create SCHEMA temporal')
print 'The schema newSchema was created in database'
end
else
print 'The schema newSchema already exists in database'
go
In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button

Unable to find where triggers are stored in sql server 2008

I want to delete and modify previously created triggers but i cant find them anywhere in database. Where they exist and how to edit or delele them
You can find Triggers under Table node:
Under the Tables node in SSMS (SQL Server Management Studio), for each table there is a Triggers node.
You can manage your triggers from there.
Here is a better way:
select a.[name] as trgname, b.[name] as [tbname]
from sys.triggers a join sys.tables b on a.parent_id = b.object_id
Just be sure to run it against the database where you think the trigger is located.
You can also find the triggers by querying the management views in SQL Server Management Studio:
SELECT
OBJECT_NAME(object_id) 'Table name', *
FROM
sys.triggers
That gives you a list of all triggers and what table they're defined on for your current database. You can then go on to either disable or drop them.
To expand a little on the previous answers, in all the recent versions of SQL Server you can right click on a trigger and choose: Script Trigger as… ALTER To… "New Query Editor Window"
This will open an SQL script with the details of the trigger, if you read the code you will notice that it includes the ALTER syntax: ALTER TRIGGER [dbo].triggername ...
This means you can edit the SQL and press Execute to alter the trigger - this will overwrite the previous definition.
If the triggers have been built using automated tools, you may find duplicate code in the trigger definition which you will want to remove.
It is worth trying to Execute the script first before trying to edit anything, that will tell you if the trigger definition is valid. If a table or column has been renamed, things can get out of sync.
Similarly to Delete/Drop a trigger completely select: Script Trigger as… DROP To… "New Query Editor Window" and then execute it.

Resources