我在SQL Server 2008中的同一个数据库中有两个表。我想将表的内容复制到另一个具有相同模式的空表,但是当我执行语句时
OleDbDataAdapter da = new OleDbDataAdapter("select * into dbo.leadmastersnew from dbo.leadmasters", myConnection);
它会抛出一个错误,表示该表已存在于数据库中。
我希望如果表已经存在,则应删除该表,因为上面的SQL查询创建了表并将内容复制到该表。
请建议
我的代码是
private void button5_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = new OleDbConnection("File Name=E:\\Vivek\\ImplementUdl\\ImplementUdl\\new.udl");
try
{
myConnection.Open();
if (myConnection.State == ConnectionState.Open)
MessageBox.Show("Connection opened successfully!");
else
MessageBox.Show("Connection could not be established");
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter("select * into dbo.leadmastersnew from dbo.leadmasters", myConnection);
da.Fill(ds);
MessageBox.Show("Data Copied!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
myConnection.Close();
}
return;
}
答案 0 :(得分:2)
如果它还不存在,我会创建一个空表,然后复制数据。如果可能,请不要使用udl文件进行连接,而是将连接字符串存储在其他地方
using(var conn = new SqlConnection("<connectionstring>"))
using(var cmd = new SqlCommand(@"
if object_id('dbo.leadmastersnew') is null
begin
select * into dbo.leadmastersnew from dbo.leadmasters where 1=2
alter table dbo.leadmastersnew add primary key (<key>)
end
insert into dbo.leadmastersnew
select *
from dbo.leadmasters lm
where not exists(select * from dbo.leadmastersnew lmn where lm.<key> = lmn.<key>)", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
请注意,在where子句中,您需要填写正确的<key>
列。我还为新表添加了一个主键约束,因为select into不会复制源表的主键/索引。
答案 1 :(得分:1)
我只想在一个SQL语句中完成所有操作:
IF OBJECT_ID(N'dbo.leadmastersnew', 'U') IS NOT NULL
DROP TABLE dbo.leadmastersnew;
SELECT *
INTO dbo.leadmastersnew
FROM dbo.leadmasters;
答案 2 :(得分:1)
您的问题的解决方案可能是此查询
EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
之后,如果返回True,则表存在。现在您需要运行插入查询
String query = "INSERT INTO dbo.The_table(id,username,password,email) VALUES(@id,@username,@password, @email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");
command.ExecuteNonQuery();
如果原始语句返回false,则需要在runnig insert查询之前运行create table查询。 create table查询看起来很像这样。
string queryString = @"
CREATE TABLE MyTable
(
Id int IDENTITY(1,1) PRIMARY KEY CLUSTERED,
Name varchar(50)
)";
SqlCommand command = new SqlCommand(
queryString, connection);
command.ExecuteNonReader();
答案 3 :(得分:1)
要回答SQL为什么不起作用的实际问题,您收到错误的原因是因为您有以下内容:
select * into dbo.leadmastersnew from dbo.leadmasters
SQL将其解释为创建表leadmastersnew
的命令,然后填充它。如果您已经开始使用解决方案,那么只需将SQL更改为以下内容:
if object_id('dbo.leadmastersnew') is not null begin drop table dbo.leadmastersnew end select * into dbo.leadmastersnew from dbo.leadmasters
这将测试表是否存在,如果是,则将其删除,然后再次创建并填充表。这不是一种非常干净的做事方式,但如果这就是你想要的,那么这就可以做到。