如何更改列以在VB.NET中包含主键 [英] How do I alter a column to include a primary key in VB.NET

查看:101
本文介绍了如何更改列以在VB.NET中包含主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个alter table语句来改变我当前的列以包含一个主键。



这里是我的代码:

$ /

I have tried to create an alter table statement to change my current column to include a primary key.

here is my code:

sqlcon.Open()
           Dim cmdDBCC As New System.Data.SqlClient.SqlCommand("ALTER TABLE [" & dtname & "] ADD PRIMARY KEY(" & dtcolumn & ")", sqlcon)
           cmdDBCC.ExecuteNonQuery()
           sqlcon.Close()







但是,当我运行代码时它不起作用并跳过执行查询。有没有一个很好的方法来改变列以包含PK?



我尝试过:



我试图使用上面的代码,我也尝试使用代码约束,但它们都没有工作。






However, when I run the code it does not work and skips over the executenonquery. Is there a good approach to altering a column to include a PK?

What I have tried:

I have tried to use the code above and I have also tried to use constraint with the code and neither of them worked.

sqlcon.Open()
           Dim cmdDBCC As New System.Data.SqlClient.SqlCommand("ALTER TABLE [" & dtname & "] ADD CONSTRAINT PK_" & dtname & " PRIMARY KEY(" & dtcolumn & ")", sqlcon)
           cmdDBCC.ExecuteNonQuery()
           sqlcon.Close()

推荐答案

您需要定义'不起作用'。首先发出您的字符串并在SQL Server管理工作室中运行它以确保您的SQL是正确的。如果是,请检查您的代码以运行它。



此代码不适用于已有主键的表。你只能有一个。我想不出这个代码存在的任何世俗理由。为什么需要动态设置?
You need to define 'does not work'. First emit your string and run it in SQL Server management studio to make sure your SQL is correct. If it is, then check your code to run it.

This code will not work on a table that has a primary key already. You can only have one. I can't think of any earthly reason for this code to exist. Why do you need to set it dynamically?


这篇关于如何更改列以在VB.NET中包含主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆