我从下面得到这个错误消息“传递给 LEFT 或 SUBSTRING 函数的长度参数无效”。任何人都可以给我一个提示,这是什么原因造成的,我该如何解决?
string cmdText = @"Declare @SqlString nvarchar(2500)
, @AreaDelimiter char(1)
, @AreaFilter nvarchar(max);
Select @AreaDelimiter = ','
If (@AreaName Not Like '*')
Begin
Set @AreaName = @AreaName + @AreaDelimiter
Set @AreaFilter = ''
While LEN(@AreaName) > 0
Begin
If (Len(@AreaFilter) > 0)
Begin
Set @AreaFilter = @AreaFilter + ' Or Area Like ''' +
LTRIM(SubString(@AreaName, 1,
CharIndex(@AreaDelimiter, @AreaName) - 1)) + '%'''
End
Else
Begin
Set @AreaFilter = 'Area Like ''' +
LTRIM(SubString(@AreaName, 1,
CharIndex(@AreaDelimiter, @AreaName) - 1)) + '%'''
End
Select @AreaName = SUBSTRING(@AreaName, CharIndex(@AreaDelimiter,
@AreaName) + 1, Len(@AreaName))
End
End"
上面的代码继续使用 else 语句和其他有效的操作:)
这是我的 C# 代码:
string area = "AREA1,AREA2,AREA3";
using (SqlConnection conn = new SqlConnection(domain.getDecryptedSqlConnectionString(domain.name + passPhrase)))
{
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
System.Globalization.CultureInfo cInfo = new System.Globalization.CultureInfo("pt-BR");
DateTime dt = DateTime.Parse(startDate, cInfo);
DateTime da = DateTime.Parse(endDate, cInfo);
cmd.Parameters.Add("Interval", SqlDbType.Int).Value = interval;
cmd.Parameters.Add("IntervalUnit", SqlDbType.VarChar).Value = intervalUnit;
cmd.Parameters.Add("StartDate", SqlDbType.DateTime).Value = dt.ToShortDateString();
cmd.Parameters.Add("EndDate", SqlDbType.DateTime).Value = da.ToShortDateString();
cmd.Parameters.Add("tbName", SqlDbType.VarChar).Value = domain.alarmTableName;
cmd.Parameters.Add("AreaName", SqlDbType.VarChar).Value = area;
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
using (DataTable tb = new DataTable())
{
try
{
conn.Open();
adapter.Fill(tb);
return tb;
}
catch (Exception ex)
{
return tb;
}
finally
{
conn.Close();
}
}
}
}
}
解决了,我只是改变
cmd.Parameters.Add("AreaName", SqlDbType.VarChar).Value = area;
为了
cmd.Parameters.Add("AreaName", SqlDbType.VarChar, -1).Value = area;