Database Still 'exists' After Deletion

Apr 14, 2006

hi

Basically, I create a database with sql, then I delete it manually(not via sql statment. This is a problem which I realise. In fact, you can't delete the database because the VS 2005 still is using it) I run the same code again,
then it says the database still exists, even it is physically destroied.

------Here is the errors:
System.Data.SqlClient.SqlException: Database 'riskDatabase' already exists.
at System.Data.SqlClient.SqlConnection.OnError(SqlExc eption exception, Boolea
n breakConnection)

------The evidence that the database doesn't exist physically:
Unhandled Exception: System.Data.SqlClient.SqlException: Cannot open database "riskDatabase" requested by the login. The login failed.

------The code:
/*
* C# code to programmically create
* database and table. It also inserts
* data into the table.
*/

using System;
using System.Collections.Generic;
using System.Text;

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace riskWizard
{
public class RiskWizard
{
// Sql
private string connectionString;
private SqlConnection connection;
private SqlCommand command;

// Database
private string databaseName;
private string currDatabasePath;
private string database_mdf;
private string database_ldf;

public RiskWizard(string databaseName, string currDatabasePath, string database_mdf, string database_ldf)
{
this.databaseName = databaseName;
this.currDatabasePath = currDatabasePath;
this.database_mdf = database_mdf;
this.database_ldf = database_ldf;
}

private void executeSql(string sql)
{
// Create a connection
connection = new SqlConnection(connectionString);

// Open the connection.
if (connection.State == ConnectionState.Open)
connection.Close();

connection.ConnectionString = connectionString;
connection.Open();

command = new SqlCommand(sql, connection);
try
{
command.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
}

public void createDatabase()
{
string database_data = databaseName + "_data";
string database_log = databaseName + "_log";

connectionString
= "Data Source=.\SQLExpress;Initial Catalog=;Integrated Security=SSPI;";

string sql = "CREATE DATABASE " + databaseName + " ON PRIMARY"
+ "(name=" + database_data + ",filename=" + database_mdf + ",size=3,"
+ "maxsize=5,filegrowth=10%)log on"
+ "(name=" + database_log + ",filename=" + database_ldf + ",size=3,"
+ "maxsize=20,filegrowth=1)";

executeSql(sql);
}

public void dropDatabase()
{
connectionString
= "Data Source=.\SQLExpress;Initial Catalog=" + databaseName + ";Integrated Security=SSPI;";

string sql = "DROP DATABASE " + databaseName;

executeSql(sql);
}

// Create table.
public void createTable(string tableName)
{
connectionString
= "Data Source=.\SQLExpress;Initial Catalog=" + databaseName + ";Integrated Security=SSPI;";

string sql = "CREATE TABLE " + tableName +
"(userId INTEGER IDENTITY(1, 1) CONSTRAINT PK_userID PRIMARY KEY," +
"name CHAR(50) NOT NULL, address CHAR(255) NOT NULL, employmentTitle TEXT NOT NULL)";

executeSql(sql);
}

// Insert data
public void insertData(string tableName)
{
string sql;

connectionString
= "Data Source=.\SQLExpress;Initial Catalog=" + databaseName + ";Integrated Security=SSPI;";

sql = "INSERT INTO " + tableName + "(userId, name, address, employmentTitle) " +
"VALUES (1001, 'Puneet Nehra', 'A 449 Sect 19, DELHI', 'project manager') ";
executeSql(sql);

sql = "INSERT INTO " + tableName + "(userId, name, address, employmentTitle) " +
"VALUES (1002, 'Anoop Singh', 'Lodi Road, DELHI', 'software admin') ";
executeSql(sql);

sql = "INSERT INTO " + tableName + "(userId, name, address, employmentTitle) " +
"VALUES (1003, 'Rakesh M', 'Nag Chowk, Jabalpur M.P.', 'tester') ";
executeSql(sql);

sql = "INSERT INTO " + tableName + "(userId, name, address, employmentTitle) " +
"VALUES (1004, 'Madan Kesh', '4th Street, Lane 3, DELHI', 'quality insurance mamager') ";
executeSql(sql);
}

public static void Main(String[] argv)
{
string databaseName = "riskDatabase";
string currDatabasePath = "E:\liveProgrammes\cSharpWorkplace\riskWizard\A pp_Data";
// Need to be more flexible.
string database_mdf = "'E:\liveProgrammes\cSharpWorkplace\riskWizard\ App_Data\riskDatabase.mdf'";
string database_ldf = "'E:\liveProgrammes\cSharpWorkplace\riskWizard\ App_Data\riskDatabase.ldf'";

RiskWizard riskWizard = new RiskWizard(databaseName, currDatabasePath, database_mdf, database_ldf);
riskWizard.createDatabase();
riskWizard.createTable("userTable");
riskWizard.insertData("userTable");
//riskWizard.dropDatabase();
}
}
}

View 1 Replies


ADVERTISEMENT

Control If A SQL Database Exists Before Its Creation Or Deletion

Aug 17, 2006

Hi,
I'm using SQL Server 2005, and I would like to understand how to create and to drop a database without errors:
Infact, if I try to create a database that already exists, SQL Server throws the error "Impossible to create the database because it already exists", and if I try to drop a database that doesn't exist, SQL Server throws the error "Impossible to drop the database because it doesn't esist".
Before creating or dropping a database, I should control if it exists or not...
Is there a method to do that?
I found that such control for a table is the following one (in this case, I drop the table only if it exists):

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Table1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Table1]

I tried to adapt the statement to the database case, modifying it as follows:
if exists (select * from dbo.sysobjects where id = object_id(N'[Database1]') and OBJECTPROPERTY(id, N'IsDatabase') = 1)
drop database [Database1]

but it didn't function (it was a blind attempt).
Can you suggest me a statement to do that?
Thank you very much

View 3 Replies View Related

Database Deletion

Apr 15, 2008

While performing import actions I had a system freeze, when the system returned the sessions had been closed and the database had vanished, with the help of support we recovered the database only to find that the original project ID had a suffix attached ( Original 40/0110, New 40/0110-1 ), when I try to return it to it's original numbering convention it says it has to be a unique number which suggests to me it is not deleted but hiding in the background, can the original be recovered or is it possible to renumber the recovered database, I have searched the whole of the databases and the original is nowhere to be seen.

View 1 Replies View Related

Deletion/Rename Of Master Database.

Nov 19, 2007

Hi All,

Can we have an sql server installation where we dont have a master database. Can the complete data dictionary be stored in another database , or put it other way can master database be renamed.

I have a need to assume that there will always be a master database for any SQL server instance. Want to confirm whether this assumption is true or not.

Thanks in advance.

Chandrakant Karale.

View 4 Replies View Related

An Attempt To Attach An Auto-named Database For File (file Location).../Database.mdf Failed. A Database With The Same Name Exists, Or Specified File Cannot Be Opened, Or It Is Located On UNC Share.

Sep 2, 2007

Greetings, I have just arrived back into the country (NZ) and back into ASP.NET.
 I am having trouble with the following:An attempt to attach an auto-named database for file (file location).../Database.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
It has only begun since i decided i wanted to use IIS, I realise VWD comes with its own localhost, but since it is only temporary, i wanted a permanent shortcut on my desktop to link to my intranet page.
 Anyone have any ideas why i am getting the above error? have searched many places on the internet and not getting any closer.
Cheers ~ J
 

View 3 Replies View Related

Database With The Same Name Exists

Apr 12, 2007

Hi guys,What is this errorAn attempt to attach an auto-named database for file C:inetpubwwwrootMediaApp_DataLibrary.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

View 3 Replies View Related

Check If Value Exists In Database?

Dec 9, 2006

Hi,

I'm wondering is there a command that I can use to check if a certain value exists in the database? Something that returns true or false perhaps?

SELECT * FROM Customers WHERE ID ='1'

Ok so that's simple, but how can I return a true or false if '1' is a value that exists in the db?

thanks.

View 5 Replies View Related

Verify If Database Exists

Nov 23, 2005

Hi,Is there a simple way to verify if a database exists?I'm writing a stored procedure that will accept a database name as an inputparameter,and create the database if it does't already exist.--Message posted via http://www.sqlmonster.com

View 2 Replies View Related

How To Check If Data Already Exists In Database?

Dec 8, 2006

I was able to get this code to work but now I get a SQL error if you try to submit the same information twice.  How can I add a message saying that the "email" already exists in database without the SQL error?     protected void Button1_Click1(object sender, EventArgs e)    {        SqlConnection conn =            new SqlConnection("Data Source=TECATE;Initial Catalog=subscribe_mainSQL; User Id=maindb Password=123456; Integrated Security=SSPI");        SqlCommand cmd = new SqlCommand("INSERT INTO [main] (, [userid], [fname], [lname], [degree]) VALUES (@email, @userid, @fname, @lname, @degree)", conn);                    conn.Open();            cmd.Parameters.AddWithValue("@email", email.Text);            cmd.Parameters.AddWithValue("@userid", uscid.Text);            cmd.Parameters.AddWithValue("@fname", fname.Text);            cmd.Parameters.AddWithValue("@lname", lname.Text);            cmd.Parameters.AddWithValue("@degree", degree.SelectedItem.Value);            int i = cmd.ExecuteNonQuery();            conn.Dispose();        }   

View 5 Replies View Related

How Do I Know If A Table Exists In A SQL Server Database?

Jul 11, 2005

I need to do some processing but only if a specific table 'table1' exists in the SQL Server database. How can I check if this  'table1' exists using  either ADO.Net code or  SQL Server query?

View 12 Replies View Related

Checking If An Entry Exists In A Database

Apr 22, 2006

I would like to be able to check if a certain entry exists in a SQL table. Ideally, the output would be a boolean so I can use it in an IF statement which would tell it what to do depending on whether or not the entry exists. Thanks for anyone that helps. :)

View 6 Replies View Related

Populating A Database With Data From Db If A Value Exists

Nov 16, 2004

Hi all,

I have a table where I want to populate it with data (certain fields) from another table. But I only want to populate the table if there is data in a certain field in the table I wish to get the data from.

How exactly would I do this test? Would an I have to perform an IF statement to test if the field contains a value first?

Thanks

Tryst

View 2 Replies View Related

Dev Code For Database Exists Checks

Mar 1, 2006

I want to check to see if a database exists in SQL Server 2005 Express... using VB.NET (or C#)... Can not use the SQLConnection Object... because I get a Failed Login Attempt... regardless if the DB does not exist or if it is because the User Login is incorrect

Is there some way to check to see if the Database exists (is attached) to the SQL Server 2005 Express Engine?

ward0093

View 3 Replies View Related

An Attempt To Attach An Auto-named Database For File...failed. A Database With The Same Name Exists, Or Specified File Cannot Be

Mar 24, 2006

I know allot of folks are having this problem and I tried lots of things but nothing works. I understand the problem is coping the SQL Express on another server is the problem - I just not sure what to do?

Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42

This is the last statement on the Stack Trace:

SqlException (0x80131904): An attempt to attach an auto-named database for file e:wwwdata81d0493fwwwApp_DataTestDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +735091

I checked my server forum and they said I had to name a database:
Example: Database=(unique name);

But this didn't work either.

I just tried a simple web project that has only one database and one table in SQL Express with one sqldatasource and one datagrid. It works fine on my pc but when I use the copy function in Visio Studio 2005 Pro - I can't run the site on the remote server: www.myjewelrydirect.com

I tried coping the database manually. I tried disconnecting the database before I copy it. Below is my connection statement:

<connectionStrings>
<add name="TestDB" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|TestDatabase.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

With all the comments in these forums - this must be a bug.

I have been working on this problem for over 2 weeks - HELP!



View 1 Replies View Related

How To Check If Querystring Variable Exists In Database

Feb 18, 2006

hi. i'm building a news section for some friends of mine. i list all the news items on the main page in a gridview. i've made a custom edit linkbutton that sends the user to an edit page, passing the news id as a quarystring variable. on the edit page i first check if the querystring variable contains an id at all. if not, i redirect the user to the main page. if an id is passed with the querystring, i fetch the matching news item from the database and place it in a formview control for editing.so far, so good. but what if someone types a random id in the querystring? then the formview won't show up and i'd look like a fool. :) therefore, i need some kind of check to see if the id exists in the database. if not redirect the user back to the main page... so i started thinking: i could check the databsae in a page_load procedure. if all is well, then display the news item. since the formview is automatically filled with the correct data, does that mean that i call the database two times? i mean, one for checking if the news item exists, and one for filling the formview. logically, this would be a waste of resources.help is appreciated.

View 3 Replies View Related

User Or Role Already Exists In The Current Database

Oct 9, 2000

Hi!
I've restored a backup from server A in server B. In server A I used to have a db_owner, called sitebase. After restoring the backup in server B, I created the user sitebase again and tried to grant him db_owner through Server Manager but I got the error: user or role already exists in the current database.
How can I avoid this situation and grant db_owner to him?
Thanks,
Fábio

View 1 Replies View Related

How To Check Whether Server Is Exists With Some Table In Particular Database.

May 29, 2006



hi,



I want to know through applicaiton how to check whether the Server named"Myserver" is Exists with Database named "MyDatabase" with Tables named ('Table1','Table2','Table3').

For any Database like (MS Access, Oracle, MS SQL-Server,MySQL)..



Please help me.....



thank's in advance.......

Paresh Patel.

Paresh.onmail@hotmail.com

View 1 Replies View Related

Log Shipping Alert Firing For Database That No Longer Exists

Nov 8, 2006

I have an error 14421 (database has restore threshold for 45 minutes and has not restored in more than "so many" minutes)firing for a database that no longer exists. How can I remove this alert? I have other log shipping plans that are running and so I can't delete the Log shipping alert job.

View 4 Replies View Related

How To Fix &#34;Error 15023: User Or Role &#39;%&#34; Already Exists In The Current Database

Sep 20, 2001

I used a backup copy of our production DB (residing in our prod machine) to do a database RESTORE to our test DB (residing in our test machine). This step was successful.
However when I tried to access the test DB via Peoplesoft application, I am unable to logon. Only then did I notice that all the users, with the exception of "sa", were gone.
When I attempted to add a user via Enterprise Manager's Action - Add Database User, I get the message, "Error 15023: User or role '%' already exists in the current database.
What's the best way to fix this without resorting to copying the source server's master database (If i do this, I risk clobbering some other DB's that are present in the target server but not in source server)?
Any help you can provide will be greatly appreciated!!!

View 2 Replies View Related

Flustered... A Database With The Same Name Exists, Or Specified File Cannot Be Opened, Or It Is Located On UNC Share.

Dec 5, 2006

Hello everyone,

I have been playing with a Standard Version of VS 2005 and SSE 2005 and I just cannot get these two to interact together well. I am sure it is a noob problem but I have seen this error addressed on this forum and I am just not getting it. Here is exactly what I am doing.

I want to create a database within SSE using the Management Studio. Then, I want to connect to it with VS2005. Both SSE and VS2005 are local. I just cant seem to get this to work.

I always seem to get this error "An attempt to attach an auto-named database for file C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDataSecond.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."

One thing... I create the website with Location: HTTP. I don't even know anymore why I do this.. I think because I like to be able to pull up a browser and get to my app. Other than that I am doing nothing special. However, I get the above error when I hit F5 to run the app inside VS2005.

Is there someplace where a complete noob can find a thorough and simple covering of this? Again, I have read through some of the previous posts on this and I don't understand too many of them and it seems as if there are at least 13 causes of which I don't know which one I have. Help!

Thanks.

View 30 Replies View Related

How Can You Find Active Connections To A Database So You Don't Have To Wait To Get A Failure When One Exists.

May 8, 2008

Is there a way to find active connection to a database so you don't have to wait for a restore or similar operation to fail. (Which take forever).?



Is there a SMO method or a transact SQL command or something that can be used in an application to detect active connections?



I don't want to have to wait forever to get a failure when you can't perform a operation that require that there be no active connection such detach a database. I want to be able to tell when I can perform a operation which requires no active connection and when I need to use a task without out dropping the connection like copying the schema using SMO methods.



However if there are no connection I can perform a detach copy and attach to create a new database which is considerable faster.

View 5 Replies View Related

SQL Server 2012 :: Count From Multiple Tables For Same Column Exists In Database?

May 19, 2014

i have database which has 25 tables. all tables have productid column. i need to find total records for product id = 20003 from all the tables in database.

View 9 Replies View Related

SSIS Database Transfer Error - Role Exists Even Though DB Is Being Overwritten In Task.

Mar 9, 2006



Can't get over this error, and net searches reveal other postings similiar, but no answers.

SSIS database transfer task (with overwrite) from SQL 2k source to SQL 2k5 destination fails with:



Error: The Execute method on the task returned error code 0x80131500 (ERROR : errorCode=-1073548784 description=Executing the query "CREATE ROLE [RFRSH_USER] " failed with the following error: "User, group, or role 'RFRSH_USER' already exists in the current database.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. helpFile= helpContext=0 idofInterfaceWithError={8BDFE893-E9D8-4D23-9739-DA807BCDC2AC}). The Execute method must succeed, and indicate the result using an "out" parameter.

The error seems the same regardless if the destination DB exists or not!

Anyone have a solution?





View 12 Replies View Related

Embedded SQL Server Express Deployment - Unhandled Exception: Database Already Exists

Mar 7, 2007

Good Afternoon.

I am trying to write a short application within which I would like to embed a SQL Server Express database, all of which would be deployed via ClickOnce through a web site. The installation process seems to be working without trouble, including installation of the .NET Framework 2.0 and SQL Server Express 2005.

When the application launches on the new machine, however, I get a big Microsoft .NET Framework "Unhandled exception" error dialog box that indicates the database already exists and that the database file could not be attached. I am working with a clean virtual machine that I know has never had the database installed on it.

I fear I am overlooking something quite straightforward, but since this is the first time I have ever attempted to build a data-bound application, I am not sure where I am going wrong.

Perhaps the source of the problem, or a related problem, might be revealed even when I run the application in debug mode from within Visual Studio. I can run the application once, but if I try to run it again, I get an error when I try to open the database connection that is similar in content (database already exists...could not attach). I can run the SSEUtil and detach the database and then run the application again in debug mode and it works no problem (the first time!).

Lastly, if I install the application on the machine on which it was developed and make sure the database is detached, it will run without any trouble (even repeatedly). But, on a new blank machine, there is no database listed that matches my database name, so I cannot try to detach anything!?

My apologies for such a novice question!

Sean

View 3 Replies View Related

Integration Services :: Opening A Rowset For Failed - Check That Object Exists In Database

Mar 14, 2014

I have a SSIS package where im importing data from MS access database file .MDB. I chose Microsoft JET 4.0 OLEDB provider. When i select a table and preview the data, im getting the below error.

Error at Data Flow Task [OLE DB Source [1]]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E09.

Error at Data Flow Task [OLE DB Source [1]]: Opening a rowset for "_tblDateDateEarnedMismatch" failed. Check that the object exists in the database.

But it is working for the other tables .

View 3 Replies View Related

Deletion

Nov 6, 2007

Hi all,

I have a table in xyz database and there is no column in table like creation_date or modified_date.

The problem is I want to delete records which has been added in the table before 1st jan 2007.

The size of table is 85 GB

Immediate help would be appriciable.

Regards,
Frozen

View 9 Replies View Related

Restrict Deletion

Mar 11, 2007

What would be the best practice to prevent users who didn't create a record in sql from deleting? When a record is created I have the username who created the record in one of the fields. I was thinking maybe a query?
 
Thank you in advance.

View 8 Replies View Related

Deletion Problem

Jun 4, 1999

It is an option to set deletion without getting logged since I have problem to delete two years historical data and would like to keep this year data on my 80MB rows. Actually I create a new table to get copy one-year data and I truncated the old table. I am wondering if there is other better way to do this task.

TIA,

Stella Liu

View 2 Replies View Related

Replication Without Deletion

Mar 19, 2007

Hello there,

We are currently setting up out production server to the following requirements:

1. Every month, delete records that haven't been changed in the last 90 days.
2. Replicate insert statements to a backup database which will keep track of all data, and act as an archive/data warehouse.

The first step is easy, as it is just a script that checks the date of the last change on each row. However, the second step is a bit more tricky. We tried setting up replication between two test databases, but we ran into the following problem: Whenever old data has been deleted in the production database, the replication agent deletes it in the data warehouse database too.

Is it possible to override or disable this, so data is only inserted/updated, and not deleted? No applications using the database deletes records, so database integrity should not be a problem.


Thanks for your time,

Ulrik Rasmussen

View 2 Replies View Related

DB Deletion Time

Jun 4, 2008

Is there an option to find out the deleted DBs on a server?

------------------------
I think, therefore I am - Rene Descartes

View 14 Replies View Related

Deletion In Trigger

Oct 12, 2013

table1 has a PK_tbl1 which matches FK_tbl1 in table2 and the relationship is one to one. Like this:

table1 has columns of UnitId, Code ...
table2 has columns of ItemID, UnitId ...

So if I need remove an item from table1 I must remove the matched one in table2 first.

delete from table2 where UnitId = xxx
delete from table1 where UnitId = xxx

Now I need create a trigger on table1 for deletion:

CREATE Trigger [dbo].[Table1_Delete]
ON [dbo].[Table1]
FOR DELETE
As

[code]....

View 2 Replies View Related

How To Prevent Db Deletion

Nov 22, 2006

Hi

I want to try and protect myself from my own stupidity. I have a number of sql databases, but one is LIVE. It is easy to drop tables but I want to set something (e.g. a password) which will help prevent me from dropping tables on the live database.

Any help/direction here would be appreciated.

View 8 Replies View Related

Deletion Of Duplicate Row

Jul 23, 2005

Hi Everyone,I have a table in which their is record which is exactly same.I want to delete all the duplicate keeping ony 1 record in a table.ExampleTable AEmpid currentmonth PreviousmonthSupplimentarydays basic158 2001-11-25 00:00:00.000 2001-10-01 00:00:00.000 2.004701.00158 2001-11-25 00:00:00.000 2001-10-01 00:00:00.000 2.004701.00158 2001-11-25 00:00:00.000 2001-10-01 00:00:00.000 2.004701.00I want to delete 2 rows of above table.How can I achieve that.Any suggestion how can i do that.Thank you in advanceRichard

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved