2017-08-03 108 views
-5

我的C#代码粘贴如下:我得到“1附近的语法错误”。“错误

SqlConnection con = new SqlConnection("Data Source=pawan-pc;Initial Catalog=App91;Integrated Security=True"); 
try 
{ 
    SqlCommand cmd = new SqlCommand("sp_gettinglogsfromdevice", con); 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.Parameters.AddWithValue("@tablename","DeviceLogs_"+comboBox_Attendance_SelMonth.Text+"_"+combobox_Attendance_SelectYear.Text); 
    cmd.Parameters.AddWithValue("@fromduration",datetimepicker_att_From.Value.Date); 
    cmd.Parameters.AddWithValue("@Toduration",datetimepicker_att_To.Value.Date); 

    DataRowView drow = (DataRowView)combobox_att_events.SelectedValue; 
    string l = drow.Row.ItemArray[0].ToString(); 


    SqlCommand cmd1 = new SqlCommand(); 
    cmd1.Connection = con; 
    con.Open(); 


    cmd1.CommandText = "select WorkCode from WorkCodes where WorkCodeName='"+l+"'"; 
    SqlDataReader reader = cmd1.ExecuteReader(); 

    dk = new DataTable(); 
    dk.Load(reader); 



    cmd.Parameters.AddWithValue("@WorkCode", dk.Rows[0][0]); 

    SqlDataReader reader1 = cmd.ExecuteReader(); 
    DataTable dp =new DataTable(); 
    dp.Load(reader1); 

    datagridview_att_attendance.DataSource=dp; 

引用的存储过程粘贴如下:

create procedure sp_gettinglogsfromdevice 
(
    @tablename varchar(75), 
    @fromduration datetime, 
    @Toduration datetime, 
    @WorkCode nvarchar(100) 
) 
As 
Begin 
Exec('select UserId,LogDate,WorkCode from ' 
    [email protected]+' where LogDate between ' 
    [email protected]+' and '[email protected]+' and WorkCode = '[email protected]); 
End 
Go 

荫实际上走的是表的名称动态地在我的数据库中的表会自动创建名称DeviceLogs_(月)_(年)为创建的日志的每个月。请帮助我这个错误。我已经看到无数帖子,但我似乎无法包装我的头沿这个想法

+0

哪个SQL命令导致此错误?该命令中执行的确切SQL代码是什么? – David

+3

如果你要像那样执行它,你需要在你的日期附近引用引号。但是,你的代码就像SQL注入一样。您应该使用'sp_executesql'来代替。 – mjwills

+0

@David看起来像'exec'行,该日期时间和字符串的连接会破坏sql。 – bradbury9

回答

2
Exec('select UserId,LogDate,WorkCode from ' 
[email protected]+' where LogDate between ' 
[email protected]+' and '[email protected]+' and WorkCode = '[email protected]); 

应改为:

declare @statement nvarchar(4000) 

set @statement = N'select UserId,LogDate,WorkCode from ' 
    [email protected]+' where LogDate between @fromduration and @Toduration and WorkCode = @WorkCode' 

EXEC sp_executesql @statement,N'@fromduration datetime, @Toduration datetime, @WorkCode nvarchar(100)', @fromduration, @Toduration, @WorkCode; 

为确保日期和工作代码正确传递。

+0

是的,但没有人注意到第一个错误是在尝试执行存储过程之前。 – Crowcoder

+0

好吧,我想我不能确定。它看起来像OP与我混淆,但现在可能不是。道歉。 – Crowcoder

+0

1可能是因为日期以1 @Crowcoder开头。他试图执行的查询类似于'select UserId,LogDate,TableName所在的WorkCode,其中LogDate在1/1/2000之间'等。 – mjwills