Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 错误,尝试插入时字符串或二进制数据将被截断_Sql_Sql Server - Fatal编程技术网

Sql 错误,尝试插入时字符串或二进制数据将被截断

Sql 错误,尝试插入时字符串或二进制数据将被截断,sql,sql-server,Sql,Sql Server,我正在使用以下行运行data.bat文件: Rem Tis batch file will populate tables cd\program files\Microsoft SQL Server\MSSQL osql -U sa -P Password -d MyBusiness -i c:\data.sql data.sql文件的内容是: insert Customers (CustomerID, CompanyName, Phone)

我正在使用以下行运行data.bat文件:

Rem Tis batch file will populate tables

cd\program files\Microsoft SQL Server\MSSQL
osql -U sa -P Password -d MyBusiness -i c:\data.sql
data.sql文件的内容是:

   insert Customers
            (CustomerID, CompanyName, Phone)
             Values('101','Southwinds','19126602729')
还有8行类似的行用于添加记录

当我使用
start
run
cmd
c:\data.bat
运行此命令时,我收到以下错误消息:

1>2>3>4>5>....<1 row affected>
Msg 8152, Level 16, State 4, Server SP1001, Line 1
string or binary data would be truncated.

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>
1>2>3>4>5>。。。。
Msg 8152,16级,状态4,服务器SP1001,第1行
字符串或二进制数据将被截断。
另外,我显然是个新手,但是
Level#
state#
的意思是什么,我如何查找上面的错误消息:8152?

每当你看到这个消息

字符串或二进制数据将被截断

想想你自己。。。该字段不够大,无法容纳我的数据


检查customers表的表结构。我认为您会发现一个或多个字段的长度不够大,无法容纳您试图插入的数据。例如,如果Phone字段是一个varchar(8)字段,并且您尝试在其中输入11个字符,则会出现此错误

在其中一个
INSERT
语句中,您试图在字符串(
varchar
nvarchar
)列中插入过长的字符串


如果仅仅看一下脚本就不清楚哪个
INSERT
是违规者,那么可以计算错误消息之前出现的
行数。获得的数字加上一就得到了语句编号。在您的情况下,似乎是第二次插入导致了错误。

另一种情况下,您可能会出现以下错误:

select a, b, c into #table1
from #table0

insert into #table1
    select a, b, c from #table2
    union
    select a, c, b from #table3
我也有同样的错误,原因是在从联合接收数据的INSERT语句中,列的顺序与原始表不同。如果将表3中的顺序更改为a、b、c,您将修复错误

select a, b, c into #table1
from #table0

insert into #table1
    select a, b, c from #table2
    union
    select a, c, b from #table3

我有这个问题,尽管数据长度比字段长度短。
原来问题是另一个日志表(用于审计跟踪),由主表上的触发器填充,其中的列大小也必须更改。

有些数据无法放入数据库列(小)。要找出问题所在并不容易。如果使用C#和Linq2Sql,则可以列出将被截断的字段:

首先创建助手类:

公共类SqlTruncationExceptionWithDetails:ArgumentOutOfRangeException
{
公共SqlTruncationExceptionWithDetails(System.Data.SqlClient.SqlException内部,DataContext上下文)
:base(internal.Message+“”+GetSqlTruncationExceptionWithDetailsString(上下文))
{
}
/// 
///来自以下链接的部分代码
/// http://stackoverflow.com/questions/3666954/string-or-binary-data-would-be-truncated-linq-exception-cant-find-which-fiel
/// 
/// 
/// 
静态字符串GetSqlTruncationExceptionWithDetailsString(DataContext上下文)
{
StringBuilder sb=新的StringBuilder();
foreach(context.GetChangeSet()中的对象更新。更新)
{
FindLongString(更新,sb);
}
foreach(在context.GetChangeSet().Inserts中插入对象)
{
长字符串(插入,sb);
}
使某人返回字符串();
}
公共静态void FindLongStrings(对象testObject、StringBuilder sb)
{
foreach(testObject.GetType().GetProperties()中的var propInfo)
{
foreach(propInfo.GetCustomAttributes中的System.Data.Linq.Mapping.ColumnAttribute属性(typeof(System.Data.Linq.Mapping.ColumnAttribute),true))
{
if(attribute.DbType.ToLower().Contains(“varchar”))
{
字符串dbType=attribute.dbType.ToLower();
int numberStartIndex=dbType.IndexOf(“varchar(“)+8;
int numberndindex=dbType.IndexOf(“)”,numberstartdex);
string lengthString=dbType.Substring(numberStartIndex,(numberndex-numberStartIndex));
int maxLength=0;
int.TryParse(lengthString,out maxLength);
string currentValue=(string)propInfo.GetValue(testObject,null);
如果(!string.IsNullOrEmpty(currentValue)&&maxLength!=0&¤tValue.Length>maxLength)
{
//绳子太长了
sb.AppendLine(testObject.GetType().Name+“+propInfo.Name+”+currentValue+“Max:”+maxLength);
}
}
}
}
}
}
然后准备用于提交更改的包装:

公共静态类DataContextensions
{
公共静态无效SubmitChangesWithDetailException(此DataContext DataContext)
{
//http://stackoverflow.com/questions/3666954/string-or-binary-data-would-be-truncated-linq-exception-cant-find-which-fiel
尝试
{
//这可能在数据截断时失败
dataContext.SubmitChanges();
}       
catch(SqlException SqlException)//何时(SqlException.Message==“字符串或二进制数据将被截断。”)
{
if(sqlException.Message==“字符串或二进制数据将被截断。”)//仅适用于EN windows-如果您运行的是不同的窗口语言,请在具有EN区域性的线程上调用sqlException.getMessage
抛出新的SqlTruncationExceptionWithDetails(sqlException,dataContext);
其他的
投掷;
}
}
}
准备全局异常处理程序和日志截断详细信息:

受保护的无效应用程序\u错误(对象发送方,事件参数e)
{
异常ex=Server.GetLastError();
字符串消息=例如消息;
//TODO-记录到文件
}
最后使用代码:

Datamodel.SubmitChangesWithDetailException();

在web应用程序上也出现了此问题
        using (SqlConnection conn = new SqlConnection("Data Source=XRAYGOAT\\SQLEXPRESS;Initial Catalog='Healthy Care';Integrated Security=True"))
        {
            conn.Open();

            using (var trans = conn.BeginTransaction())
            {
                try
                {
                    using cmd = new SqlCommand("", conn, trans))
                    { 

                    cmd.CommandText = "SET ANSI_WARNINGS OFF";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "YOUR INSERT HERE";
                    cmd.ExecuteNonQuery();

                    cmd.Parameters.Clear();

                    cmd.CommandText = "SET ANSI_WARNINGS ON";
                    cmd.ExecuteNonQuery();

                    trans.Commit();
                    }
                }
                catch (Exception)
                {

                    trans.Rollback();
                }

            }

            conn.Close();

        }
CREATE TYPE LocationTableType AS TABLE (...);
CREATE PROCEDURE dbo.usp_InsertProductionLocation
  @TVP LocationTableType READONLY
declare @NVPN_list as table 
nvpn            varchar(50)
,nvpn_revision  varchar(5)
,nvpn_iteration INT
,mpn_lifecycle  varchar(30)
,mfr            varchar(100)
,mpn            varchar(50)
,mpn_revision   varchar(5)
,mpn_iteration  INT
-- ...
) INSERT INTO @NVPN_LIST 
SELECT  left(nvpn           ,50)    as nvpn
        ,left(nvpn_revision ,10)    as nvpn_revision
        ,nvpn_iteration
        ,left(mpn_lifecycle ,30)
        ,left(mfr           ,100)
        ,left(mpn           ,50)
        ,left(mpn_revision  ,5)
        ,mpn_iteration
        ,left(mfr_order_num ,50)
FROM [DASHBOARD].[dbo].[mpnAttributes] (NOLOCK) mpna
select foo, bar
into tmp_new_table_to_dispose_later
from my_table