2016-11-17 61 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