2013-05-01 65 views
-1

我想讓我的一個表中的字段/變量傳輸到另一個表。變量是當前用戶的用戶標識。這兩張桌子之間有關係。當用戶註冊一個賬戶時,就爲他們創建了一個UserId。然後我希望用戶能夠存儲關於他們自己的其他細節(存儲在不同的表中)。這些項目應該鏈接到用戶。我如何讓當前用戶的UserId附加到他們提交給其他表的細節上?這是自生成的SQL命令爲我做的Visual Studio:Microsoft SQL確保用戶標識在兩個表中相同

SelectCommand="SELECT [Bhousenum], [Bstreetname], [Bcity], [Bcounty], [Bcountry], [Dhousenum], [Dstreetname], [Dcity], [Dcounty], [Dcountry], [Dpostcode], [Bpostcode], [mobilenum], [credittype], [creditname], [creditnum], [securitycode], [creditexpiry], [dob], [UserId] FROM [Customers] WHERE ([UserId] = @UserId)" 
     DeleteCommand="DELETE FROM [Customers] WHERE [UserId] = @UserId" 
     InsertCommand="INSERT INTO [Customers] ([Bhousenum], [Bstreetname], [Bcity], [Bcounty], [Bcountry], [Dhousenum], [Dstreetname], [Dcity], [Dcounty], [Dcountry], [Dpostcode], [Bpostcode], [mobilenum], [credittype], [creditname], [creditnum], [securitycode], [creditexpiry], [dob], [UserId]) VALUES (@Bhousenum, @Bstreetname, @Bcity, @Bcounty, @Bcountry, @Dhousenum, @Dstreetname, @Dcity, @Dcounty, @Dcountry, @Dpostcode, @Bpostcode, @mobilenum, @credittype, @creditname, @creditnum, @securitycode, @creditexpiry, @dob, @UserId) WHERE [UserId] = @UserId" 
     UpdateCommand="UPDATE [Customers] SET [Bhousenum] = @Bhousenum, [Bstreetname] = @Bstreetname, [Bcity] = @Bcity, [Bcounty] = @Bcounty, [Bcountry] = @Bcountry, [Dhousenum] = @Dhousenum, [Dstreetname] = @Dstreetname, [Dcity] = @Dcity, [Dcounty] = @Dcounty, [Dcountry] = @Dcountry, [Dpostcode] = @Dpostcode, [Bpostcode] = @Bpostcode, [mobilenum] = @mobilenum, [credittype] = @credittype, [creditname] = @creditname, [creditnum] = @creditnum, [securitycode] = @securitycode, [creditexpiry] = @creditexpiry, [dob] = @dob WHERE [UserId] = @UserId"> 
+1

http://en.wikipedia.org/wiki/Foreign_key - 請閱讀此處,它應該開始落實到位:) – Dave 2013-05-01 10:35:50

回答

1

設計關聯的表時,請使用外鍵約束,例如參見:

w3schools.com/sql/sql_foreignkey.asp

1

我從問題不解的是,你要使用的ID在你futher查詢創建用戶時,如果是這樣的話,那麼你必須使用下面的輸出參數在用戶插入查詢

SELECT @NewUserID = SCOPE_IDENTITY() // this commands return newly added id 

該行應該寫在查詢的末尾。

如何實現這一目標,如果你在代碼中使用的SqlDataSource然後

<asp:SqlDataSource ...> 
    <InsertParameters> 
    ........other parameters 
    <asp:Parameter Direction="Output" Name="NewUserID " Type="Int32" /> 
    </InsertParameters> </asp:SqlDataSource> 

,如果你想使用存儲過程,你可以寫爲

ALTE PROCEDURE dbo.Addusers(
    .....other parameters 
    @NewProductID int OUTPUT 
) 

,並添加此ID到其他表中,您必須在這些表中創建外鍵。並使用這個號碼,如果你需要的Infor這個讓我知道

0

使用「輸出」與存儲過程參數的任何futher插入到這些表

外鍵添加命令

user_id int FOREIGN KEY REFERENCES Userss(user_Id) 

。當您插入詳細信息時,請將您的用戶標識返回到前端,然後使用此標識號執行其他交易。

例如:

create proc <procedure name> 
(
    @name varchar(max), 
    @OutUserID int output 
) 
as 
begin 
    insert into <table name> values (<your values>) 
    set @OutUserID=scope_identity() 
end 

此SP將得到你插入了一個用戶ID,但要記住「SCOPE_IDENTITY」只能插入語句和主鍵你的汽車增量必須上。

也可以使用多個輸出參數。

相關問題