Showing posts with label program. Show all posts
Showing posts with label program. Show all posts

Friday, March 30, 2012

How to control MS SQL Server DataBases permissions through visual basic program

Hello,

Could someone help me to view, add, delete, and modify users of SQL Server DataBase and permissions of them on this database through Visual Basic Programming

Because I want to do VB application through which I will view, add,delete, and modify users of SQL Server DataBase and their permissions on this database.

Thank you very very muchYou can use the system stored procedures.|||Originally posted by rnealejr
You can use the system stored procedures.

Thank you very much Mr. rnealejr for your reply.

Would you like to send me a sample code in visual basic to view ,for example, users of SQL Server DataBase and their permissions??

I will be thankful|||Which version of sql server are you using 7 or 2000 ?|||Originally posted by rnealejr
Which version of sql server are you using 7 or 2000 ?
Hello, Mr. rnealejr
I use MS SQL Server 2000.
Also, I have a problem with SQL Server.
I have about 50 tables and views in an Oracle DataBase and I have tried to translate them to SQL Server DataBases.
They were translated succefully but there was two problems :
1- Key constraints were not translated? (i.e. the destination SQL Server database became without primary key and foreign key constraints and aother constraints)
2- Also, views are translated into tables not into view ??

Could you slove these problems?

After I get more information I will be able to serve your good forum with good posts becuase until now I am student

Thank you very much|||How did you translate from oracle to sql server ?|||You can use sp_helpuser, sp_helplogins - use the ado command object.|||Originally posted by rnealejr
How did you translate from oracle to sql server ?

Yes
I have used DTS Wizard to do this translation but tables were translated without constraints and also views were translated into tables instead of corresponding views although all tables, from whcih views get data, are available in the translated database.

Thank you very much Mr.

Monday, March 26, 2012

How to connect to SQL Database with C#?

Hi, I am trying to connect to an SQL Database with my C# program, and am having the following problems.

1) Sometimes it connects fine, other times it fails to connect. I am using Integrated Security / Windows Login.

2) I am trying to pass a Select Statement (Which works from SQL Server Management Studio), but it doesn't seem to work in my program. My code doesn't appear to do anything really...

3) When I use only the code that was generated by VS, it loads all the information into the dataGridView, but I want to filter it using the Select Statement.

Here is the code generated by VS:

private void Form1_Load(object sender, EventArgs e)
{
this.collectionTableAdapter.Fill(this.DBDataSet.Collection);
}

Here is my code:

Code Snippet

private void Form1_Load(object sender, EventArgs e)
{
//Connect to the database for Collections Table
SqlConnection thisConnection = new SqlConnection(@."Server=(local)\sqlexpress;Integrated Security=True;" +
"Database=DB");

//Create DataAdapter Object
SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT Number AS [#], Image1 AS [Image], Title1 AS [Title], Issue1 AS [Issue] FROM Table1 WHERE Tab = 'Tab1'", thisConnection);

//Create DataSet to contain related data tables, rows, and columns
DataSet thisDataSet = new DataSet();

//Fill DataSet using query defined previously for DataAdapter
thisAdapter.Fill(thisDataSet, "Collection");
foreach (DataRow theRow in thisDataSet.Tables["Collection"].Rows)
{
Console.WriteLine(theRow["Number"] + "\t" +
theRow["Image1"] + "\t" +
theRow["Title1"] + "\t" +
theRow["Issue1"]);
}

//Close Connection
thisConnection.Close();
}

One other thing, I don't know if this helps, but it appears that more often than not, it fails to log in to the database when I open the application the first time. If I exit out of the failure notice, then open the application again, it loads the data into the dataGridView (Not the data I want mind you, but at least I can connect to the database... lol).

Thank you.
|||

the very first thing you need to check is the connection string....

Refer : http://www.connectionstrings.com/?carrier=sqlserver2005

And also check the user /login credential

Madhu

|||What error you get when it fails to connect?|||Thank you, I will take a look at that. I have read a lot about this, but for whatever reason have had no luck getting this to work.

Here are the error messages I am getting. I sometimes log in to the server fine, usually on a second attempt, when I can't login I get one of these errors.

1) Cannot open database "DB" requested by the login. The login failed.
Login failed for user '__'.

2) Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Thank you.
|||

Try to set timeout=0 in web.config and also set query time out=0 in sql server.

See this http://www.aspnettutorials.com/tutorials/database/connect-sql-datasource-csharp.aspx link for relevant connection infrmation.

|||Thanks, I'll give that a shot and take a look at that link. Does it matter that this is an application, not a website?

Thank you.

|||I'm sorry, I'm still very confused by this. Where should I put the timeout = 0? Isn't it important to have a timeout period? Shouldn't it be able to access the database within the timeout period? Should I delete the dataGridView and associated controls that VS added to my project automatically? I'm not sure what I should be doing. I enter the code in as examples outline, but it still doesn't do anything. Here is my most recent code:

private void Form1_Load(object sender, EventArgs e)

string strCon = @."Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Resources\DB.mdf;Integrated Security=True;User Instance=True";

string strSQL = “select * from table1”;

SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);

SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

// Populate a new data table and bind it to the BindingSource.

DataTable table = new DataTable();

table.Locale = System.Globalization.CultureInfo.InvariantCulture;

dataAdapter.Fill(table);

dbBindingSource.DataSource = table;

// Resize the DataGridView columns to fit the newly loaded content.

dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

// you can make it grid readonly.

dataGridView1.ReadOnly = true;

// finally bind the data to the grid

dataGridView1.DataSource = dbBindingSource;

Thank you.


|||I have also tried this:

Code Snippet

// create an open the connection
SqlConnection conn =
new SqlConnection(@."Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Resources\DB.mdf;Integrated Security=True;User Instance=True");

conn.Open();

// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Number AS [#], Image AS [Image], Title AS [Title], FROM table1 WHERE Tab = '1'";
command.CommandType = CommandType.Text;

// execute the command that returns a SqlDataReader
SqlDataReader reader = command.ExecuteReader();

// display the results
while (reader.Read())
{
string output = reader.ToString();
Console.WriteLine(output);
}

// close the connection
reader.Close();
conn.Close();

This didn't work either.
|||

Try this:

SqlConnection conn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI; Initial Catalog=pubs");

Replace "Localhost" with your server name, if you have a named instance try giving it in single codes.

|||Hi and thank you very much for your response. I tried that and get this error:

Cannot open database "pubs" requested by the login. The login failed.
Login failed for user '_'.

I tried replacing "pubs" with my database name, but that gave me the same error. I don't understand this. No matter what I do I don't seem to be able to get this to work. What is SSPI by the way?

Thank you.
|||

Alright, thats looks ok

Connect to SQL Server 2005 MS go to security >> logins >> check your windows userid exists in there (hoepfully yes if your server is on the same machine, but still check once) >> right click on the user id >> click on properties >> check what all database rights that user id has >> if your target DB is not checked give the acecss >> select the role you want to give if required or leave it as is if you can live with public role

|||o SSPI is Security Support Provider Interface|||O.K., thank you very much for your help. I followed your instructions and am not entirely sure what I am looking at.

I have several users under Login:

My name and computer login is Michael. The following shows up as a login:

MICHAEL\SQLServer2005MSSQLUser$MICHAEL$SQLEXPRESS

I clicked on Properties of this user and selected User Maping, which listed several databases. I checked the box for this database and it was set to Public.

Is all this going to be necessary if I install this application on another machine? I would like to make this able to be easily distributable. Should I not use the Windows Login?

Thank you.

|||

Well that is all up to what roles you want to have, how you want to setup the security for SQL Server or your application considering the options provided by Microsoft in DOT NET and also in SQL Server.

But lets get on to the main point, doing that help you getting connected to the database thru your application?

sql

how to connect to a remote sql DB

Hi all,

myDB is located atX:\Program Files\Microsoft SQL Server\MSSQL\Data\myDB.mdf
and my code is located at : C:\Inetpub\wwwroot\applicationfolder
how do I code my server.mapPath?

Btw, can I get VS 2005 to detect the server path when using server solution.Thanks

sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath("X:\Program Files\Microsoft SQL Server\MSSQL\Data\myDB.mdf"))
dbconn.Open()
sql = "SELECT * FROM myTable"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
myDB.DataSource = dbread
myDB.DataBind()
dbread.Close()
dbconn.Close()
end sub

One big problem you are pointing to Access database which lets you map the path and SQL Server which controls the path so if your database is Access you can map the path, if it is SQL Server you cannot map the path because the database is not the runtime the relational engine is the runtime. Hope this helps.

Wednesday, March 21, 2012

How to connect database under Windows Authentication?

Hi, all. I develop my JDBC program under SQL SERVER Authentication using Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection con = DriverManager.getConnection("jdbc:sqlserver://dataserver:1433; DatabaseName=database", username, password);
It works well.
After my company update the database to SQL SERVER 2005 using Windows Authentication. My program sucks.
I want to know the format of JDBC connectivity code for Windows Authentication, as similar as the code I post above? Anyone can help me?

Hi there,

As far as I am aware, the SQL Server 2005 JDBC driver does not currently support Windows Authentication. Checking out the documentation I found here seems to indicate that Windows Auth doesn't work as setting the integratedSecurity property to "true" (implying Windows Auth) produces an exception.

You could try jTDS (http://jtds.sourceforge.net/faq.html). The project seems to be dead at the moment but you can still download the required files. It supports Windows Auth and in the connection string you have to use the domain property and specify what domain you are on (same domain as the SQL Server you are trying to connect to, of course).

The relevant information is all in the FAQ (the jTDS link I gave above).

Good luck & sorry I couldn't be of more help at the mo.

How to conncet two PC's to share SQL server database using VB

Sir,

I am a beginer to SQL Server, as well as to networking. I have a VB program to manage a SQL server database.
I need to share database informations using a second PC. Both PC's are installed with network cards and connected with a cross network cable.

Now I need to configure the two PC's to share information and to send reports to a printer.

Pl help me to solve this problem anyone who knows.

Thanks.

Kusman

Quote:

Originally Posted by kusmanf

Sir,

I am a beginer to SQL Server, as well as to networking. I have a VB program to manage a SQL server database.
I need to share database informations using a second PC. Both PC's are installed with network cards and connected with a cross network cable.

Now I need to configure the two PC's to share information and to send reports to a printer.

Pl help me to solve this problem anyone who knows.

Thanks.

Kusman


that's mater of databse connection

you can use DSN connection to solve ur prob

Monday, March 19, 2012

how to configure one-way merge replication?

With the appropriate replacements, this should do the job:
C:\Program Files\Microsoft SQL Server\80\COM>replmerg -
Publisher DH1791628 -PublisherDB xxxPublisher -
Publication xxxPublishertClients -Subscriber DH1791628 -Su
bscriberDB sub1 -Distributor DH1791628 -DistributorLogin
sa -DistributorPassword sa -ExchangeType 2
Rgds,
Paul Ibison SQL Server MVP, www.replicationanswers.com
(recommended sql server 2000 replication book:
http://www.nwsu.com/0974973602p.html)
Thank you Paul responding back. I tried the script but I keep getting this
error 'the process could not connect to the distributor.sql server does not
exist or access denied'. which login and password are we supposed to be
using? is it same as what the sqlserver agent is running as?
here is my script:
C:\Program Files\Microsoft SQL Server\80\COM>replmerg -publisher westcoast
-publisherDB westcoast -publication westcoast -subcriber testwestcoast
-subscriberDB testwestcoast -Distributor westcoast -distributorLogin sa
-distributorpassword sa -exchangeType 2
I set the log in and password to what my sqlserveragent was running under.
It still doesnt work. Please give me your suggestion on this. Thanks
Jessy
"Paul Ibison" wrote:

> With the appropriate replacements, this should do the job:
> C:\Program Files\Microsoft SQL Server\80\COM>replmerg -
> Publisher DH1791628 -PublisherDB xxxPublisher -
> Publication xxxPublishertClients -Subscriber DH1791628 -Su
> bscriberDB sub1 -Distributor DH1791628 -DistributorLogin
> sa -DistributorPassword sa -ExchangeType 2
> Rgds,
> Paul Ibison SQL Server MVP, www.replicationanswers.com
> (recommended sql server 2000 replication book:
> http://www.nwsu.com/0974973602p.html)
>
|||Is this push or pull?
According to the script you have a server called
westcoast, which has a published database called
westcoast and a publication called westcoast - is this
correct?
It looks like it must be a pull, as your distributor is
also westcoast.
If you want to use trusted security for the merge agent,
then set the -SubscriberSecurityMode parameter to 1. It
defaults to SQL Server security, so in the original
script I put sa and a password of sa - don't laugh - I
saw this and blank recently.
Rgds,
Paul Ibison
|||Paul, I am still getting the same error. "could not connect to the
distributor'.
My publisher and publication is called westcoast. I have 'pull' from
subscriber. i am setting my distributor on the same server as my publisher.
Where do you look to check the distributor properties. I check under
Distribution Agent, but its blank. Is this is correct? When you set up the
merge replication the distribution db automactically is generated. what is
this used for?
I set the subscribersecuritymode to 0 because i am using the sql server
authenticaton. I am still having problems setting this up correctly.
Jessy
"Paul Ibison" wrote:

> Is this push or pull?
> According to the script you have a server called
> westcoast, which has a published database called
> westcoast and a publication called westcoast - is this
> correct?
> It looks like it must be a pull, as your distributor is
> also westcoast.
> If you want to use trusted security for the merge agent,
> then set the -SubscriberSecurityMode parameter to 1. It
> defaults to SQL Server security, so in the original
> script I put sa and a password of sa - don't laugh - I
> saw this and blank recently.
> Rgds,
> Paul Ibison
>
|||Can you log into testwestcoast and open up a query
analyser window (connection) to westcoast, using your
values for -DistributorLogin and -DistributorPassword to
log in and check that this works.
The distribution database holds merge metadata and things
like the next identity range to be used, and you'll need
a valid sql server login for your publisher/distributor
for this to work.
Rgds,
Paul Ibison SQL Server MVP, www.replicationanswers.com
(recommended sql server 2000 replication book:
http://www.nwsu.com/0974973602p.html)
|||Paul - I was able to run script w/o any errors. however its not doing what
i want. I need to only pull from the publisher to the subscriber. If i add
new records in subscriber it gets updated to the publisher. I dont want
data send back to the publisher. What am i doing wrong here?
C:\Program Files\Microsoft SQL Server\80\COM>replmerg -Publisher [TN5347]
-PublisherDB [westcoast] -Publication [westcoast] -Subscriber [TN5347]
-SubscriberDB [testwestcoast] -subscriberlogin sa -subscriberpassword
mypassword -subscribersecuritymode 0 -subscriptionType 1 -Distributor
[TN5347] -distributorlogin sa -distributorpassword sibu27 -exchangetype 2
Here is what the result was after running the script :
Connecting to Subscriber 'TN5347'
Connecting to Distributor 'TN5347'
Initializing
Connecting to Publisher 'TN5347'
Retrieving publication information
Retrieving subscription information
The merge process is cleaning up meta data in database 'westcoast'.
The merge process cleaned up 0 row(s) in MSmerge_genhistory, 0 row(s) in
MSmerge
_contents, and 0 row(s) in MSmerge_tombstone.
The merge process is cleaning up meta data in database 'testwestcoast'.
The merge process cleaned up 0 row(s) in MSmerge_genhistory, 0 row(s) in
MSmerge
_contents, and 0 row(s) in MSmerge_tombstone.
Downloading data changes to the Subscriber
No data needed to be merged.
No data needed to be merged.
"Paul Ibison" wrote:

> Can you log into testwestcoast and open up a query
> analyser window (connection) to westcoast, using your
> values for -DistributorLogin and -DistributorPassword to
> log in and check that this works.
> The distribution database holds merge metadata and things
> like the next identity range to be used, and you'll need
> a valid sql server login for your publisher/distributor
> for this to work.
> Rgds,
> Paul Ibison SQL Server MVP, www.replicationanswers.com
> (recommended sql server 2000 replication book:
> http://www.nwsu.com/0974973602p.html)
>
|||Jessy,
I think we're almost there. Please try -exchangetype 1.
Rgds,
Paul Ibison
"Jessy" <Jessy@.discussions.microsoft.com> wrote in message
news:9395EC21-B200-4ED4-9413-1F3FE22912B3@.microsoft.com...[vbcol=seagreen]
> Paul - I was able to run script w/o any errors. however its not doing
> what
> i want. I need to only pull from the publisher to the subscriber. If i
> add
> new records in subscriber it gets updated to the publisher. I dont want
> data send back to the publisher. What am i doing wrong here?
> C:\Program Files\Microsoft SQL Server\80\COM>replmerg -Publisher [TN5347]
> -PublisherDB [westcoast] -Publication [westcoast] -Subscriber [TN5347]
> -SubscriberDB [testwestcoast] -subscriberlogin sa -subscriberpassword
> mypassword -subscribersecuritymode 0 -subscriptionType 1 -Distributor
> [TN5347] -distributorlogin sa -distributorpassword sibu27 -exchangetype 2
> Here is what the result was after running the script :
> Connecting to Subscriber 'TN5347'
> Connecting to Distributor 'TN5347'
> Initializing
> Connecting to Publisher 'TN5347'
> Retrieving publication information
> Retrieving subscription information
> The merge process is cleaning up meta data in database 'westcoast'.
> The merge process cleaned up 0 row(s) in MSmerge_genhistory, 0 row(s) in
> MSmerge
> _contents, and 0 row(s) in MSmerge_tombstone.
> The merge process is cleaning up meta data in database 'testwestcoast'.
> The merge process cleaned up 0 row(s) in MSmerge_genhistory, 0 row(s) in
> MSmerge
> _contents, and 0 row(s) in MSmerge_tombstone.
> Downloading data changes to the Subscriber
> No data needed to be merged.
> No data needed to be merged.
>
> "Paul Ibison" wrote:
|||Paul- i tried the exchangetype 1 but its not working. I mean everything is
updated on both ends. I thought i should be using exchangeType 2 if i want
the publisher to only send data and not get data back. 'A value of 2
indicates that the agent should download data changes from the Publisher to
the Subscriber'. Do we need to reintalize in order for this to work?
Also I am using numeric id 'yes(not for replication)'. I know rowguid is
generated when we set up merge replication. however i noticed the numeric
id's show up twice on the table. If table 1 generated person 1 with id 1
this number is also added to the other table 2 as the same number. but table
2 already has a person with the same number 1. Is this correct?
Lastly, i previously deleted a replication on another database and ran some
store procedures sp_removedbreplication to clean up the merge replication
from publisher and subscriber. But the publications are still displayed in
the publisher folder and snapshot agent folder under replication monitor. So
my replication monitor is showing a red 'X'. How do you get rid of the
deleted publications on the replication monitor?
"Paul Ibison" wrote:

> Jessy,
> I think we're almost there. Please try -exchangetype 1.
> Rgds,
> Paul Ibison
> "Jessy" <Jessy@.discussions.microsoft.com> wrote in message
> news:9395EC21-B200-4ED4-9413-1F3FE22912B3@.microsoft.com...
>
>
|||Jessy,
yes, this value is incorrectly reported in some places so apologies. A value
of 1 indicates uploads to publisher only, 2 means subscriber to publisher.
Actually your previous post indicates you have it set correctly! I just
assumed you'd got the values the wrong way round. "Downloading data changes
to the Subscriber" appears and not the corresponding upload message. There's
no data exchange, but does it report the same message when you add a row to
publisher and subscriber ie no uploads?
Reinitialization is not necessary. Are you using MSDE? If not, then add the
parameter to the merge agents middle step and try there.
For the identity columns, it looks like you haven't enabled automatic range
management. You'll need this to partition the ranges. The best thing here is
to drop your subscription and then edit the article properties (elipsis
button) to enable a large identity range for the publisher and subscriber.
To get rid of the red x running sp_MSload_replication_status normally clears
this error or restarting the sql server service also works - tempdb needs
clearing out and this'll rebuild it.
Rgds,
Paul Ibison SQL Server MVP, www.replicationanswers.com
(recommended sql server 2000 replication book:
http://www.nwsu.com/0974973602p.html)
|||where do I look for the message report? I dont see any messages displayed
when i am inserting to the subscriber or publisher. I just click on the "!"
and the whatever i entered in the subscriber is still showing on the
publisher. How do i fix this?
I am using MSDE for just testing purpose. When i get this replication
working the way i want i will i try this on the server box. I believe thats
a standard/enterprise SQL Server.
"Paul Ibison" wrote:

> Jessy,
> yes, this value is incorrectly reported in some places so apologies. A value
> of 1 indicates uploads to publisher only, 2 means subscriber to publisher.
> Actually your previous post indicates you have it set correctly! I just
> assumed you'd got the values the wrong way round. "Downloading data changes
> to the Subscriber" appears and not the corresponding upload message. There's
> no data exchange, but does it report the same message when you add a row to
> publisher and subscriber ie no uploads?
> Reinitialization is not necessary. Are you using MSDE? If not, then add the
> parameter to the merge agents middle step and try there.
> For the identity columns, it looks like you haven't enabled automatic range
> management. You'll need this to partition the ranges. The best thing here is
> to drop your subscription and then edit the article properties (elipsis
> button) to enable a large identity range for the publisher and subscriber.
> To get rid of the red x running sp_MSload_replication_status normally clears
> this error or restarting the sql server service also works - tempdb needs
> clearing out and this'll rebuild it.
> Rgds,
> Paul Ibison SQL Server MVP, www.replicationanswers.com
> (recommended sql server 2000 replication book:
> http://www.nwsu.com/0974973602p.html)
>
>

Monday, March 12, 2012

how to configure a server as distributor

When configuring my SQL Server as a distributor I get the following
error:
Error 14113:Could not execute 'copy "
C:\Program Files\Microsoft SQL Server\MSSQL\DATA\DISTMDL.MDF"
"C:\Program Files\Microsoft SQL Server\MSSQL\DATA\distribution.MDF"'.
Check
'instdist.out' in the install directory
I could not find a file named instdist.out in the install directory.
Please Help!!
Thanks.
The setup will require you to be a system administrator - are you logged on
as one?
Also has the distribution database been created?
Also, check that you have sufficient room for a copy of the distribution
database.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .
|||I've logged in as system administrator.
distmodel database is also there and have sufficient space on my disk.
but still the problem has not been solved.
please show me a way.
thanx
jeff
Paul Ibison wrote:
> The setup will require you to be a system administrator - are you logged on
> as one?
> Also has the distribution database been created?
> Also, check that you have sufficient room for a copy of the distribution
> database.
> Cheers,
> Paul Ibison SQL Server MVP, www.replicationanswers.com .
|||I'd set it up manually and see where the issue is:
sp_adddistributor
sp_adddistributiondb
sp_adddistpublisher
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .
|||First disable distribution from the Replication menu
Then try below commands in query analyser
sp_helpserver ( to see server name)
sp_dropserver 'SERVERNAME','DROPLOGINS'
sp_addserver 'SERVERNAME','LOCAL'
Then try creating Distribution again
"Paul Ibison" <Paul.Ibison@.Pygmalion.Com> wrote in message
news:u7Y6pBCBHHA.3540@.TK2MSFTNGP03.phx.gbl...
> I'd set it up manually and see where the issue is:
> sp_adddistributor
> sp_adddistributiondb
> sp_adddistpublisher
> Cheers,
> Paul Ibison SQL Server MVP, www.replicationanswers.com .
>
|||Take the database distmodel to Offline
EggHeadCafe.com - .NET Developer Portal of Choice
http://www.eggheadcafe.com

Sunday, February 19, 2012

How to clear all database connection using SQLDMO?

Hello guys! I'm using SQLDMO to restore a database backup. The problem is, the program cannot restore the backup if there are active connections using the database. Is there are way to clear all database connections using SQLDMO (or other libraries)? Thanks in advance

You could create a storedproc in master that kills any existing spids per db, then run that proc from DMO as part of the restore job.. something like this

CREATE procedure sp_KillOldspids

@.dbName varchar (30) = NULL
AS

set nocount on

declare @.currentspid int,@.cmdstring varchar(30)

dECLARE OPENSPIDS CURSOR FOR SELECT [SPID] from [MASTER].[DBO].[SYSPROCESSES] WHERE DBID = db_id (@.dbName)
OPEN OPENSPIDS

FETCH NEXT FROM OPENSPIDS INTO @.CURRENTSPID

WHILE @.@.FETCH_STATUS = 0
BEGIN

SELECT @.cmdString = 'kill ' + convert(varchar(10), @.CURRENTspid)
IF @.@.SPID <> @.CURRENTSPID
BEGIN
EXEC (@.cmdString)
END
FETCH NEXT FROM OPENSPIDS INTO @.CURRENTSPID

END

CLOSE CURRENTSPIDS
DEALLOCATE CURRENTSPIDS

hopes this helps.