2012-07-09 105 views
-1

我有一個註冊表格,我想檢查用戶以前沒有註冊過。防止用戶註冊兩次

我的代碼在下面。我認爲存在兩個問題:(1)調用方法和(2)將參數傳遞給存儲過程。我的症狀是,這導致一個異常,說輸入參數未初始化。

create procedure fakeuser @username nvarchar(250),@codemeli nchar(10),@email  nvarchar(50), @user nvarchar(250) output,@code nchar(10)output,@mail nvarchar(50)output 
as 
if exists(select username,email,codemeli from karbar where [email protected]) 
set @[email protected] 
else if exists(select username,email,codemeli from karbar where [email protected]) 
set @[email protected] 
else if exists(select username,email,codemeli from karbar where [email protected]) 
set @mail= @email 

下面是C#代碼:

public static string confirm(string username, string email, string codemeli) 
    { 
     string constring = "data source=.;database=site;integrated security=true;"; 
     SqlConnection connection = new SqlConnection(constring); 

     // Command - specify as StoredProcedure 
     SqlCommand command = new SqlCommand("fakeuser", connection); 
     command.CommandType = CommandType.StoredProcedure; 

     SqlParameter param = new SqlParameter("@username", SqlDbType.NVarChar); 
     param.Direction = ParameterDirection.Input; 
     param.Value = username; 
     command.Parameters.Add(param); 

     SqlParameter param2 = new SqlParameter("@email", SqlDbType.NVarChar); 
     param2.Direction = ParameterDirection.Input; 
     param2.Value = username; 
     command.Parameters.Add(param2); 

     SqlParameter param3 = new SqlParameter("@codemeli", SqlDbType.NChar); 
     param3.Direction = ParameterDirection.Input; 
     param3.Value = username; 
     command.Parameters.Add(param3); 

     // Return value as parameter 
     SqlParameter returnuser = new SqlParameter("@user", SqlDbType.NVarChar); 
     returnuser.Direction = ParameterDirection.ReturnValue; 
     command.Parameters.Add(returnuser); 

     SqlParameter returncode = new SqlParameter("@code", SqlDbType.NChar); 

     returncode.Direction = ParameterDirection.ReturnValue; 

     command.Parameters.Add(returncode); 
     SqlParameter returnmail = new SqlParameter("@mail", SqlDbType.NVarChar); 
     returnmail.Direction = ParameterDirection.ReturnValue; 
     command.Parameters.Add(returnmail); 

     // Execute the stored procedure 
     connection.Open(); 
     command.ExecuteNonQuery(); 
     connection.Close(); 

謝謝。

+1

究竟是什麼不起作用?您需要使用Visual Studio調試器,SQL Server Management Studio和其他編程工具來確定哪部分代碼導致了問題。如果您發現問題並找不到解決方法,我們很樂意爲您提供幫助,但我認爲您會發現大多數人不會爲您找到問題所在。 – 2012-07-09 14:50:00

回答

1

爲@ user,@ code和@mail設置ParameterDirection=Output,並指定參數的寬度/大小/長度。

SqlParameter returnuser = new SqlParameter("@user", SqlDbType.NVarChar,100); 
returnuser.Direction = ParameterDirection.Output; 
command.Parameters.Add(returnuser); 
+0

我這樣做,但發生此異常 - > Size屬性的無效大小爲0. – quantum62 2012-07-09 14:57:34

+0

@ quantum62 - 您必須指定輸出參數的** length **。 – adatapost 2012-07-09 15:06:10

+0

非常感謝,問題解決了 – quantum62 2012-07-09 15:12:31