2016-11-17 75 views
1

刚刚发现SQL Server,刚刚发现了存储过程的美妙世界 - 它已经让我头疼了。来到这里寻求帮助。SQL Server存储过程 - C#PK - FK

场景1:给出一个表,我写了一个存储过程,并在C#中调用它来填充表。一切都按预期工作。

Country SQL table looks like this

存储过程:

CREATE PROCEDURE [dbo].[InsertRecord2] 
    @countryname nvarchar(64), 
AS 
    INSERT INTO Country(CountryName) 
    VALUES (@countryname) 

    RETURN 

调用在C#

private void button1_Click(object sender, EventArgs e) 
{ 
    readonly SqlConnection _connection = new SqlConnection(@"Data Source=REXGBASQLP042;Initial Catalog=isg_cid;Integrated Security=True"); 

    _connection.Open(); 

    SqlCommand _command = _connection.CreateCommand(); 
    _command.CommandType = CommandType.StoredProcedure; 
    _command.CommandText = "InsertRecord2"; 

    _command.Parameters.Add("@countryname", SqlDbType.NVarChar).Value = countryname.Text; 

    _command.ExecuteNonQuery(); 

    _connection.Close(); 
} 

方案2:我现在要创建一个SQL视图,包括以前Country表和另一个表,我们称之为CityCountryID,这是Country表的PK,是City表中的FK。

SQL view looks like this

存储过程:

CREATE PROCEDURE [dbo].[InsertRecord2] 
    @countryname nvarchar(64), 
    @cityname nvarchar(64) 
AS 
    INSERT INTO Country(CountryName) 
    VALUES (@countryname) 

    INSERT INTO City(CityName) 
    VALUES (@cityname) 

    RETURN 

调用在C#:

private void button1_Click(object sender, EventArgs e) 
{ 
    readonly SqlConnection _connection = new SqlConnection(@"Data Source=REXGBASQLP042;Initial Catalog=isg_cid;Integrated Security=True"); 

    _connection.Open(); 

    SqlCommand _command = _connection.CreateCommand(); 
    _command.CommandType = CommandType.StoredProcedure; 
    _command.CommandText = "InsertRecord2"; 

    _command.Parameters.Add("@countryname", SqlDbType.NVarChar).Value = countryname.Text; 
    _command.Parameters.Add("@cityname", SqlDbType.NVarChar).Value = cityname.Text; 

    _command.ExecuteNonQuery(); 

    _connection.Close(); 
} 

这里来的问题。点击按钮,我看到一个例外:

附加信息:无法将值NULL插入到'CountryID'列'isg_cid.dbo.City'列中;列不允许有空值。 INSERT失败。

好的,这很明显 - 一个PK不能为NULL。但是,当我试图插入Country表,我没有指定ID(自动递增,自动切换种子ON),所以

  1. 为什么我必须指定这个时候?和
  2. 我该怎么做?

我认为它应该在存储过程中以某种方式完成,我敢打赌,这是非常简单的解决 - 对于有SSMS经验的人来说。对我来说,搞清楚该怎么做是一件麻烦事。

感谢您的帮助!

+0

你可以给创建表脚本这两个表 – Surendra

+0

从存储过程返回1的ID,并在存储过程中2 – mybirthname

回答

1

它不是Country表中的CountryID字段,而是City表中的CountryID字段,它触发错误消息。
这是将城市与其国家连接起来的外键,并且在您插入新城时逻辑上不能没有任何价值。

因此,一种可能的方法是使用SCOPE_IDENTITY()读取为Country表设置的最后一个IDENTITY值,并使用此值在City表中设置CountryID。

您需要

CREATE PROCEDURE [dbo].[InsertRecord2] 
@countryname nvarchar(64), 
@cityname nvarchar(64) 

AS 

    INSERT INTO Country(CountryName) VALUES (@countryname) 
    INSERT INTO City(CountryID, CityName) 
    VALUES (SCOPE_IDENTITY(), @cityname) 
+1

感谢史蒂夫改设为第二SP。拷贝你的代码,但是这似乎有一个语法错误。看到图片在这里: http://imgur.com/a/xM0Dz 编辑:如果我删除SELECT,它工作得很好。谢谢! – stuckedagain