removing an object from Publication database sys.sp_droparticle and sp_dropsubscription - sql-server

SQL Server Admin is not my forte. So please bear with while I explain this
A SQL Server 2012 cluster is involved in a Change data capture ( CDC ) effort using a 3rd party CDC utility. for it to work replication needs to be turned on, without replication CDC will not work. The CDC taps some 2000+ odd tables from SQL Server in a database Db1. Out of these we found out that some 200+ tables undergo truncate and load as against increments. So we removed those from our CDC lists but since replication is turned on at DB Level we also need to remove these from publication database so that truncates happening to this exception list wont need replication switched off DB level ( aka truncates to these tables and replication can co-exist. As its known, for truncates to happen we need to switch off replication. The code is in prod so replacing truncate by delete is not an option now besides the fact that for billion row tables deletes are going to be expensive & time consuming )
The above is the requirement. So based on that if a better solution can be conceived do let me know
What I tried :
EXEC sys.sp_droparticle #publication = 'pub', #article = 'art', #force_invalidate_snapshot = 1
Error I get
Msg 14013, Level 16, State 1, Procedure sp_MSrepl_droparticle, Line 104 [Batch Start Line 2]
This database is not enabled for publication.
Another SP
DECLARE #subscriber AS sysname;
EXEC sp_dropsubscription #publication = 'AR_PUBLICATION_00010', #article = 'BPA_BRGR_RUL_GRP_R' ,#subscriber=#subscriber
Msg 14013, Level 16, State 1, Procedure sp_MSrepl_dropsubscription, Line 55 [Batch Start Line 1]
This database is not enabled for publication.
But using GUI I am able to uncheck the tables I dont want in that publication. ( right click publication --> properties --> articles --> check /uncheck whatever you want excluded ) . I dont have any subscription just there is a publication.
Whatever code I ran through GUI above I can def. run through T-SQL But I dont know what code was it that was run ? How do I get this done using a scripting approach. I have 200+ tables to deal with and unchecking em 1 by 1 ain't helping

Nearly four years late, but in case it helps anyone... I think you want sp_dropmergearticle not sp_droparticle.
EXEC sys.sp_dropmergearticle #publication = 'pub', #article = 'art', #force_invalidate_snapshot = 1
I was getting an identical error message using sp_droparticle, but sp_dropmergearticle removed the table from the publication and allowed me to delete it.

Whatever code I ran through GUI above I can def. run through T-SQL But I dont know what code was it that was run ? How do I get this done using a scripting approach.
SSMS does not have a special API. Everything it does, it does through TSQL. So use SQL Profiler to watch what SSMS does, and capture the script.

Related

Trigger cannot be created in Microsoft SQL Server Management Studio

I'm trying to run this trigger that is suppose to update a row in my customers table after a row is updated in the same table.
CREATE TRIGGER [project].updateFreeShipping
ON [project].[customers]
AFTER UPDATE
AS
BEGIN
UPDATE [project].[customers]
SET NextShippingIsFree = 1
WHERE Email IN (SELECT TOP 5 Email FROM dbo.Top10byMoney)
END
It throws the following error:
Msg 8197, Level 16, State 4, Procedure updateFreeShipping, Line 2
The object 'project.customers' does not exist or is invalid for this operation
Screenshot:
This is a clear and classical error that is raised when you execute a statement in another database that the one you usually use. Very often, beginners does not verify the contexteual database and try to create objets in master which is the default one in SSMS. Remember that SQL Server is a multi-database multi-schema RDBMS and does not require any DBlink to execute SQL scripts from one DB to another... So make a great attention to which database you contextually use !
To avoid such trouble, begin your script with the USE statement, like :
USE MyDatabase;
GO
CREATE TRIGGER [project].updateFreeShipping
ON [project].[customers]
AFTER UPDATE
AS
...
I agree to all others comments about the logic of your code which has no sense...

SQL Server Linked Server Update - terrible performance

In my SQL Server 2012 database, I have a linked server reference to a second SQL Server database that I need to pull records from and update accordingly.
I have the following update statement that I am trying to run:
UPDATE
Linked_Tbl
SET
Transferred = 1
FROM
MyLinkedServer.dbo.MyTable Linked_Tbl
JOIN
MyTable Local_Tbl ON Local_Tbl.LinkedId = Linked_Tbl.Id
JOIN
MyOtherTable Local_Tbl2 ON Local_Tbl.LocalId = Local_Tbl2.LocalId
Which I had to stop after an hour of running as it was still executing.
I've read online and found solutions stating that the best solution is to create a stored procedure on the Linked Server itself to execute the update statement rather than run it over the wire.
The problems I have are:
I don't have the ability to create any procedures on the other server.
Even if I could create that procedure, I would need to pass through all the Ids to the stored procedure for the update and I'm not sure how to do that efficiently with thousands of Ids (this, obviously, is the smaller of the issues, though since I can't create that procedure in the first place).
I'm hoping there are other solutions people may have managed to come up with given that it's often the case you don't have permissions to make changes to a different server.
Any ideas??
I am not sure, whether it can give more performance, you an try:
UPDATE
Linked_Tbl
SET
Transferred = 1
FROM OPENDATASOURCE([MyLinkedServer],'select Id, LocalId,Transferred from remotedb.dbo.MyTable') AS Linked_Tbl
JOIN MyTable Local_Tbl
ON Local_Tbl.LinkedId = Linked_Tbl.Id
JOIN MyOtherTable Local_Tbl2
ON Local_Tbl.LocalId = Local_Tbl2.LocalId

Database is in Transition state

Today I was trying to restore a database over an already existing database, I simply right clicked the database in SSMS --> Tasks --> Take Offline so I could restore the database.
A small pop up window appeared and showed Query Executing..... for sometime and then threw an error saying Database is in use cannot take it offline. From which I gathered there are some active connections to that database so I tried to execute the following query
USE master
GO
ALTER DATABASE My_DatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO
Again at this point the SSMS showed Query Executing..... for a sometime and then threw the following error:
Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'My_DatabaseName'. Try again later.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
After this I could not connect to the database through SSMS. and when I tried to Take it offline using SSMS it threw an error saying:
Database is in Transition. Try later .....
At this point I simply could'nt touch the database anything I tried it returned the same error message Database is in Transition.
I got on google read some questions where people had faced similar issue and they recommended to close the SSMS and open it again, So did I and
Since it was only a dev server I just deleted the database using SSMS and restored on a new database.
My question is what could have possibly caused this ?? and how I can Avoid this to happen in future and if I ever end up in the same situation in future is there any other way of fixing it other then deleting the whole database ???
Thank you
Check this out. This will help you release locks. Works great! https://dba.stackexchange.com/questions/57432/database-is-in-transition-error
use this
select
l.resource_type,
l.request_mode,
l.request_status,
l.request_session_id,
r.command,
r.status,
r.blocking_session_id,
r.wait_type,
r.wait_time,
r.wait_resource,
request_sql_text = st.text,
s.program_name,
most_recent_sql_text = stc.text
from sys.dm_tran_locks l
left join sys.dm_exec_requests r
on l.request_session_id = r.session_id
left join sys.dm_exec_sessions s
on l.request_session_id = s.session_id
left join sys.dm_exec_connections c
on s.session_id = c.session_id
outer apply sys.dm_exec_sql_text(r.sql_handle) st
outer apply sys.dm_exec_sql_text(c.most_recent_sql_handle) stc
where l.resource_database_id = db_id('<YourDatabase>')
order by request_session_id;
and then
for each processnumber
kill <processnumber>
Check out this article.
http://oostdam.info/index.php/sectie-blog/289-sql-error-952-8ways-to-solve-it
I use TSQL most of the time, so I have not run into this issue yet.
What version is the SQL Server database and at what patch level?
Next time, do a usp_who2 to see what threads are running.
http://craftydba.com/wp-content/uploads/2011/09/usp-who2.txt
Since the output is in a table, you can search by database.
Kill all threads using the database before the trying the ALTER statement.
A night about 6 months ago, I had a terrible time getting a 2000 database offline due to an application constantly hitting it. I eventually disabled the user account so I would not get any more logins.

Strange Issue in SSIS with WITH RESULTS SET returning wrong number of columns

So I have a stored procedure in SQL Server. I've simplified its code (for this question) to just this:
CREATE PROCEDURE dbo.DimensionLookup as
BEGIN
select DimensionID, DimensionField from DimensionTable
inner join Reference on Reference.ID = DimensionTable.ReferenceID
END
In SSIS on SQL Server 2012, I have a Lookup component with the following source command:
EXECUTE dbo.DimensionLookup WITH RESULT SETS (
(DimensionID int, DimensionField nvarchar(700) )
)
When I run this procedure in Preview mode in BIDS, it returns the two columns correctly. When I run the package in BIDS, it runs correctly.
But when I deploy it out to the SSIS catalog (the same server the database is on), point it to the same data sources, etc. - it fails with the message:
EXECUTE statement failed because its WITH RESULT SETS clause specified 2 column(s) for result set number 1, but the statement sent
3 column(s) at run time.
Steps Tried So Far:
Adding a third column to the result set - I get a different error, VS_NEEDSNEWMETADATA - which makes sense, kind of proof there's no third column.
SQL Profiler - I see this:
exec sp_prepare #p1 output,NULL,N'EXECUTE dbo.DimensionLookup WITH RESULT SETS ((
DimensionID int, DimensionField nvarchar(700)))',1
SET FMTONLY ON exec sp_execute 1 SET FMTONLY OFF
So it's trying to use FMTONLY to get the result set data ... needless to say, running SET FMTONLY ON and then running the command in SSMS myself yields .. just the two columns.
SET NOTCOUNT ON - Nothing changed.
So, two other interesting things:
I deployed it out to my local SQL 2012 install and it worked fine, same connections, etc. So it may be a server / database configuration. Not sure what if anything it is, I didn't install the dev server and my own install was pretty much click through vanilla.
Perhaps the most interesting thing. If I remove the join from the procedure's statement so it just becomes
select DimensionID, DimensionField from DimensionTable
It goes back to just sending 2 columns in the result set! So adding a join, without adding any additional output columns, ups the result set to 3 columns. Even if I add 6 more joins, just 3 columns. So one guess is its some sort of metadata column that only gets activated when there's a join.
Anyway, as you can imagine, it's driving me kind of mad. I have a workaround to load the data into a temp table and just return that, but why won't this work? What extra column is being sent back? Why only when I add a join?
Gah!
So all credit to billinkc: The reason is because of a patch.
In Version 11.0.2100.60, SSIS Lookup SQL command metadata is gathered using the old SET FMTONLY method. Unfortunately, this doesn't work in 2012, as the Books Online entry on SET FMTONLY helpfully notes:
Do not use this feature. This feature has been replaced by sp_describe_first_result_set.
Too bad they didn't follow their own advice!
This has been patched as of version 11.0.2218.0. Metadata is correctly gathered using the sp_describe_first_result_set system stored procedure.
This can happen if the specified WITH results set in SSIS identifies that there are more columns than being returned by the stored proc being called. Check your stored proc and ensure that you have the correct number of output columns as the WITH results set.

SQL Server COMPILE locks?

SQL Server 2000 here.
I'm trying to be an interim DBA, but don't know much about the mechanics of a database server, so I'm getting a little stuck. There's a client process that hits three views simultaneously. These three views query a remote server to pull back data.
What it looks like is that one of these queries will work, but the other two fail (client process says it times out, so I'm guessing a lock can do that). The querying process has a lock that sticks around until the SQL process is restarted (I got gutsy and tried to kill the spid once, but it wouldn't let go). Any queries to this database after the lock hang, and blame the first process for blocking it.
The process reports these locks... (apologies for the formatting, the preview functionality shows it as fully lined up).
spid dbid ObjId IndId Type Resource Mode Status
53 17 0 0 DB S GRANT
53 17 1445580188 0 TAB Sch-S GRANT
53 17 1445580188 0 TAB [COMPILE] X GRANT
I can't analyze that too well. Object 1445580188 is sp_bindefault, a system stored procedure in master. What's it hanging on to an exclusive lock for?
View code, to protect the proprietary...I only changed the names (they stayed consistent with aliases and whatnot) and tried to keep everything else exactly the same.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER view [dbo].[theView]
as
select
a.[column1] column_1
,b.[column2] column_2
,[column3]
,[column4]
,[column5]
,[column6]
,[column7]
,[column8]
,[column9]
,[column10]
,p.[column11]
,p.[column12]
FROM
[remoteServer].db1.dbo.[tableP] p
join [remoteServer].db2.dbo.tableA a on p.id2 = a.id
join [remoteServer].db2.dbo.tableB b on p.id = b.p_id
WHERE
isnumeric(b.code) = 1
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
Take a look at this link. Are you sure it's views that are blocking and not stored procedures? To find out, run this query below with the ObjId from your table above. There are things that you can do to mitigate stored procedure re-compiles. The biggest thing is to avoid naming your stored procedures with an "sp_" prefix, see this article on page 10. Also avoid using if/else branches in the code, use where clauses with case statements instead. I hope this helps.
[Edit]:
I believe sp_binddefault/rule is used in conjunction with user defined types (UDT). Does your view make reference to any UDT's?
SELECT * FROM sys.Objects where object_id = 1445580188
Object 1445580188 is sp_bindefault in the master database, no? Also, it shows resource = "TAB" = table.
USE master
SELECT OBJECT_NAME(1445580188), OBJECT_ID('sp_bindefault')
USE mydb
SELECT OBJECT_NAME(1445580188)
If the 2nd query returns NULL, then the object is a work table.
I'm guessing it's a work table being generated to deal with the results locally.
The JOIN will happen locally and all data must be pulled across.
Now, I can't shed light on the compile lock: the view should be compiled already. This is complicated by the remote server access and my experience of compile locks is all related to stored procs.

Resources