Alter stored procedure or function added extra blank line gap - sql

In SQL Server 2012 when I write code for stored procedure and for any function. After that when I want to alter it added extra blank line gap, that's why it seem very unacceptable lenghty..
CREATE proc sp_delete_Rte_article_admin_Latest
(
#id int
)
as
begin
if exists (select * from tblRte where Id=#id )
begin
declare #IvanID bigint
set #IvanID=(select [IvanArtId] from tblRte where Id=#id )
insert into tblRteOnDelete([IvanArtId],[StoryType],[ChannelType],[Filename],
[Headline],[PublishDate],[Title],[DocScope],[KeyWord],[Byline],[City],
[State],[StoryDate],[BodyContents],[DownloadedDate],DeleteDate)
select [IvanArtId],[StoryType],[ChannelType],[Filename],[Headline],[PublishDate],
[Title],[DocScope],[KeyWord],[Byline],[City],[State],[StoryDate],
[BodyContents],[DownloadedDate],GETDATE()
from tblIvanhoeXmlFeeds
where Id=#id
delete from tblRte where Id=#id
delete from tblUpdatedRteTopics where IvanArtId=#IvanID
delete from tblCheckAllowRte where ArticleID=#IvanID
delete from tblAddRteeApprove where ArticleID=#IvanID
return 1
end
else
begin
return 0
end
end
What should do for moving this for all time..any setting ?

I want to know Sqlserver 2012 Configuration Setting or Code Setting so that I could remove
the black Space Line ,which come after and after whern are going to alter and open again...

Related

T-SQL (SQL Server 2016) trigger for column value alter, at Insert

I am working on a SSIS project of mine. I have successfully manage to load some csv's into my database (through Integration Services in VS) and now I am trying to create a trigger in the database.
All I want to happen is: when the number of the column second_road_class is -1 I want it to change into 6. I want the trigger to fire during the inserts.
My trigger code seems to debug ok in SSMS! But when I am later trying to insert the csv's again, the second_road_class column with -1 stays as it is.
Trigger code:
CREATE TRIGGER AccidentsTrigger
ON [Accidents]
INSTEAD OF INSERT
AS BEGIN
SET NOCOUNT ON
IF (SELECT [second_road_class] FROM INSERTED) LIKE '-1'
BEGIN
UPDATE [Accidents]
SET [second_road_class] = '6'
WHERE [second_road_class] = '-1'
END
END
Thanks for any help.
You could do this with an after insert trigger.
create trigger accidentstrigger on [accidents]
after insert as
begin;
set nocount on;
if exists (select 1 from inserted where [second_road_class] = '-1')
begin;
update a
set [second_road_class] = '6'
from [accidents] as a
inner join inserted i
/* change AccidentId to the Primary Key on accidents*/
on a.AccidentId = i.AccidentId
and i.[second_road_class] = '-1';
end;
end;
go
Example using the pilots table on rextester: http://rextester.com/XKX10184

Procedure which modify existing trigger

I want to create procedure which modify existing trigger. Trigger is responsible for blocking rows from beeing updated with specific ID. I tried something like that:
CREATE PROCEDURE Change_trigger
#List_of_ids varchar(8000)
AS
ALTER TRIGGER blocks
ON ttt
INSTEAD OF update
AS
BEGIN
If (SELECT Id_ttt FROM inserted) IN (#List_of_ids)
BEGIN
raiserror('You cannot modify this record.', 12, 1)
RETURN
END
UPDATE ttt
SET
field1 = INSERTED.field1
FROM INSERTED
WHERE INSERTED.Id_ttt = ttt.Id_ttt
END
Parameter #List_of_ids would be like this: 2,3,4,5,9,52. But when I try to create this procedure I got error:
Msg 156, Level 15, State 1, Procedure Change_trigger, Line 4
Incorrect syntax near the keyword 'TRIGGER'.
The trigger is created.
This is the trigger I'd write, once.
ALTER TRIGGER blocks
ON ttt
INSTEAD OF update
AS
BEGIN
SET NOCOUNT ON
UPDATE t
SET
field1 = i.field1
FROM INSERTED i
inner join
ttt t
on i.Id_ttt = t.Id_ttt
left join
ttt_blocked on tb
on
i.Id_ttt = tb.Id_ttt
WHERE
tb.Id_ttt is null
END
Note that this trigger no longer throws an error for blocked updates but it does allow for a mixed update (some rows blocked, some rows not) to occur. There's no clean way to raise an error whilst still partially applying an update in a trigger.
Then I'd have a table (referenced above):
CREATE TABLE ttt_blocked (
Id_ttt int not null,
constraint PK_ttt_blocked PRIMARY KEY (Id_ttt)
)
And then, if necessary, I'd create a procedure to maintain this table rather than continually changing the database schema:
CREATE PROCEDURE Change_blocking
#BlockedIDs xml
AS
--Better option would be table-valued parameters
--but I've chosen to do XML today
--We expect the XML to be of the form
--<blocks>
-- <id>10</id>
-- <id>15</id>
--</blocks>
MERGE INTO ttt_blocked t
USING (select x.id.value('text()[1]','int')
from #BlockedIDs.nodes('/blocks/id') x(id)) s(Id_ttt)
ON
t.Id_ttt = s.Id_ttt
WHEN NOT MATCHED THEN INSERT (Id_ttt) VALUES (s.Id_ttt)
WHEN NOT MATCHED BY SOURCE THEN DELETE;
As I also allude to above, I'd generally recommend Table-Valued Parameters rather than XML (and either of them ahead of varchar since they're designed to hold multiple values) but it would have added even more code to this answer.
Try this..
CREATE PROCEDURE Change_trigger
#List_of_ids varchar(4000)
AS
begin
declare #sql varchar(8000)
set #sql ='
ALTER TRIGGER blocks
ON ttt
INSTEAD OF update
AS
BEGIN
if exists (SELECT Id_ttt FROM inserted where Id_ttt IN ('+#List_of_ids+'))
BEGIN
raiserror(''You cannot modify this record.'', 12, 1)
RETURN
END
UPDATE ttt
SET
field1 = INSERTED.field1
FROM INSERTED
WHERE INSERTED.Id_ttt = ttt.Id_ttt
END' ;
exec (#sql);
END

instead of trigger result output

I have created my first trigger. Please see the code section for the trigger below.
The triggers and the results are as expected, except for one thing.
So when I run the code below it will not insert the values into my table so the number of records remains unchanged.
insert into MatlabSearchPath(directory, userName)
values('madeup', 'default')
In the messages window though I get two lines. I don't understand why I see two lines and in particular 1 row affected - the number of records in my table hasn't changed?
(0 row(s) affected)
(1 row(s) affected)
Trigger
create trigger trDefaultPathInsert on DVLP_QES.dbo.MatlabSearchPath
instead of insert
as
begin
declare #defCount int
declare #retVal int
select #defCount = count(userName) from inserted where userName = 'Default'
if (#defCount > 0)
begin
select #retVal = count(HostName) from DVLP_QES.dbo.UserHostName where HostName = HOST_NAME()
if (#retVal > 0)
begin
insert into MatlabSearchPath select * from inserted
end
else
begin
insert into MatlabSearchPath select * from inserted where inserted.userName <> 'Default'
end
end
end
Update
I should mention that there a 3 triggers on this table, one is the trigger above the other one is a delete & the last one is an update
Your trigger does the following:
Counts records you are trying to insert, where userName equals 'Default'
In your case, count is 1.
Pay attention to your collation - if it's case sensitive, you are going to skip that whole branch of code.
If you enter the if branch, next thing trigger checks is if there are rows in UserHostName table where HostName equals host name of your client; pay attention that you don't think it should be host name of your server or something like that
If you enter the TRUE-branch, it should insert everything to the table; however, if not, it shouldn't insert anything. Of course, except if the collation is case sensitive, then revert the logic.
I I were you, I would add PRINT statements into trigger, just to make sure how does it execute.
create trigger trDefaultPathInsert on DVLP_QES.dbo.MatlabSearchPath
instead of insert
as
begin
declare #defCount int
declare #retVal int
select #defCount = count(userName) from inserted where userName = 'Default'
PRINT '#defCount'
PRINT #defCount
if (#defCount > 0)
begin
select #retVal = count(HostName) from DVLP_QES.dbo.UserHostName where HostName = HOST_NAME()
PRINT '#retVal'
PRINT #retVal
if (#retVal > 0)
begin
PRINT 'TRUE-BRANCH'
insert into MatlabSearchPath select * from inserted
end
else
begin
PRINT 'FALSE-BRANCH'
insert into MatlabSearchPath select * from inserted where inserted.userName <> 'Default'
end
end
EDIT
It seems that the message about rows affected can't be controlled inside the trigger. Even the standard SET NOCOUNT ON on the trigger beginning won't stop it from showing. This gave me notion that the message is a result of the trigger being successfully finished by calling it with X rows, where X will eventually be in the X row(s) affected message.
This SO question furtherly confirms the problem.
The situation here if the first message indicating cero is because the instead of trigger is uses to ignore the insert you sent and do instead whats in the trigger
You can debug your code with management studio

T-SQL - anti-duplicate trigger

I need to write a trigger which prevents from inserting more than one record at the same time and also checks if the place is already in the database. Code compiles but it doesn't work as it should - it displays error message even if I try to add a non-existing address
Here's my code:
CREATE TRIGGER address_duplicate ON place
AFTER INSERT
AS
BEGIN
DECLARE #counter INT
SELECT #counter=COUNT(*) FROM place WHERE street IN (SELECT street FROM inserted) AND number IN(SELECT number FROM inserted)
AND city IN(SELECT city FROM inserted) AND postcode IN(SELECT postcode FROM inserted)
IF #counter>0
BEGIN
RAISERROR('This record is already in the database',1,1)
ROLLBACK
END
IF ##ROWCOUNT>1
BEGIN
RAISERROR('You can add only one record at the same time',1,2)
ROLLBACK
END
END
GO
Your logic of identifying duplicate place is not correct.
Try something like this:
select #counter= count(*) from place p join inserted n
where p.address=n.address and p.city=n.city and p.postcode=n.postcode
and p.number=n.number;
Also want you to know, using triggers to avoid duplicate can be very expensive.
Personally, I'd use a unique constraint and probably use TRY-CATCH when inserting, but if you really want to do it in a trigger, try this out:
CREATE TRIGGER address_duplicate ON place
INSTEAD OF INSERT
AS
BEGIN
DECLARE #newValue TABLE (ID INT);
IF ##ROWCOUNT > 1
BEGIN
RAISERROR('Insert cancelled. You can add only one record at the same time.',1,2);
END
ELSE
BEGIN
INSERT INTO place
OUTPUT inserted.ID INTO #newValue
SELECT *
FROM inserted
EXCEPT
SELECT *
FROM place
IF (SELECT 1 FROM #newValue) IS NULL
RAISERROR('Insert cancelled. This record is already in the database',1,1)
END
END

Create SQL Server tables and stored procedures in one script?

I have a SQL script that is setting up two database tables with their keys and constraints without any problem. I won't include the whole code but the 'skeleton' of it looks like this:
BEGIN
CREATE TABLE [table] (
)
CREATE TABLE [table2] (
)
ALTER TABLE table...
ALTER TABLE table2....
END
I am stuck trying to add stored procedures to this script though, ideally I would like to include this all within the same script. Could someone tell me how to include the following stored procedure into the above script?
CREATE PROCEDURE Test
#x int
AS
BEGIN
SELECT COUNT(*)
FROM table
END
GO
I have tried putting it towards the end of the script and have also tried with and without the BEGIN, END and GO tags but I keep getting an error that says 'incorrect syntax near PROCEDURE'.
Try it like this:
USE BDNAME
GO
BEGIN
CREATE TABLE [table] (
)
CREATE TABLE [table2] (
)
ALTER TABLE table...
ALTER TABLE table2....
END
USE BDNAME
GO
CREATE PROCEDURE Test
#x int
AS
BEGIN
SELECT COUNT(*)
FROM table
END
GO
Instead of using BEGIN END, put GO between all your Statements like Create, Alter. Also I would like to inform you that putting GO will create blocks in your script, so if you create some local variable in one block, it is not accessible in another.
CREATE Table Table1(
--Your Code
)
GO
CREATE PROCEDURE Test
#x int
AS
BEGIN
SELECT COUNT(*)
FROM Table1
END
GO
--Continue your script
Hope this helps.