搜索查询中“userId”附近的语法不正确

时间:2014-12-08 07:27:10

标签: c# sql-server

我有一个搜索查询,它会抛出此错误Incorrect syntax near 'userId'而我不知道为什么以及如何解决它。它现在正在影响其他

我的SQL查询

oCommand = new SqlCommand(@"Select us.sFieldValue5, u.sUserName, d.sName, TB_USER_CUSTOMINFO.sFieldValue2, u.nUserIdn
From TB_USER u(nolock)
left join [TB_USER_CUSTOMINFO] us(nolock) on us.nUserIdn = u.nUserIdn
left join TB_USER_CUSTOMINFO on  u.nUserIdn = TB_USER_CUSTOMINFO.nUserIdn
left join TB_USER_DEPT d(nolock) on d.nDepartmentIdn = u.nDepartmentIdn
where (u.sUserName like '%" + txtUsername.Text + @"%' or '" + txtUsername.Text + @"' = '')
and (us.sFieldValue5 like '%" + txtUserID.Text + @"%' or '" + txtUserID.Text + @"' = '')
and (d.sDepartment like '%" + sDepartment + @"%' or '" + sDepartment + @"' = '--Select Department--')
and (u.nUserIdn = " + userId + @" or " + txtusersID.Text + @" = 0)", oConnection);                                 

2 个答案:

答案 0 :(得分:4)

从参数化查询开始。如果有人在文本框中包含单引号,那么您所做的事情是非常危险的,并且根本不会起作用。 (例如txtUserID.Text ="我现在要崩溃")

oCommand = new SqlCommand(@"Select us.sFieldValue5, u.sUserName, d.sName, TB_USER_CUSTOMINFO.sFieldValue2, u.nUserIdn
            From TB_USER u(nolock)
            left join [TB_USER_CUSTOMINFO] us(nolock) on us.nUserIdn = u.nUserIdn
            left join TB_USER_CUSTOMINFO on  u.nUserIdn = TB_USER_CUSTOMINFO.nUserIdn
            left join TB_USER_DEPT d(nolock) on d.nDepartmentIdn = u.nDepartmentIdn
            where (u.sUserName like ('%' + @UserName + '%') or @UserName = '')
            and (us.sFieldValue5 like ('%' + @UserId + '%') or @UserId = '')
            and (d.sDepartment like ('%' + @Department + '%') or @Department = '--Select Department--')
            and (u.nUserIdn = @UserId or @UserId2 = 0)", oConnection);    

oCommand.Parameters.AddWithValue("@UserName", txtUsername.Text)
//etc.

答案 1 :(得分:0)

除了代码最后一行中的 UserID ,您还需要在 OR 运算符之前指定列名称。

检查以下更正的代码:

oCommand = new SqlCommand(@"Select us.sFieldValue5, u.sUserName, d.sName, TB_USER_CUSTOMINFO.sFieldValue2, u.nUserIdn
                From TB_USER u(nolock)
                left join [TB_USER_CUSTOMINFO] us(nolock) on us.nUserIdn = u.nUserIdn
                left join TB_USER_CUSTOMINFO on  u.nUserIdn = TB_USER_CUSTOMINFO.nUserIdn
                left join TB_USER_DEPT d(nolock) on d.nDepartmentIdn = u.nDepartmentIdn
                where (u.sUserName like '%" + txtUsername.Text + @"%' or '" + txtUsername.Text + @"' = '')
                and (us.sFieldValue5 like '%" + txtUserID.Text + @"%' or '" + txtUserID.Text + @"' = '')
                and (d.sDepartment like '%" + sDepartment + @"%' or '" + sDepartment + @"' = '--Select Department--')
                and (u.nUserIdn = " + userId + @" or u.nUserIdn = " + txtusersID.Text + @")", oConnection);