简体   繁体   中英

Import data from Excel to SQL Server, cannot save as decimal data type

I have a utility that imports Excel spreadsheets to SQL Server. My utility broke recently when I had to convert some fields from nvarchar to decimal.

I use c# code to call a stored procedure. My c# code:

DataTable dtChem = new DataTable();
ada.Fill(dtChem);  // Fills datatable with data from Excel
cmd.Parameters.Clear();
cmd.CommandText = "dbo.insertDataChem";
cmd.Parameters.AddWithValue("@chemResults", dtChem);
cmd.Parameters.AddWithValue("@eddName", strFileName);                                    
cmd.ExecuteNonQuery();

My stored procedure:

create PROCEDURE [dbo].[insertDataChem]
    @chemResults as dbo.udtableDataChem READONLY
    , @eddName nvarchar(100) = null
AS

BEGIN 
    INSERT INTO MY_TABLE
    SELECT cr.SampleDate, cr.*,  @eddName, CURRENT_TIMESTAMP FROM @chemResults cr
END 

And I use the following user-defined table type to store my data (I've removed a lot of fields for brevity):

CREATE TYPE [dbo].[udtableDataChem] AS TABLE(

    ...

    [MDL] [decimal](30, 15) NULL,   // data type changed
    [RL] [decimal](30, 15) NULL,    // data type changed
    [DilutionFactor] [nvarchar](200) NULL,  // original data type
    [ExpectedValue] [nvarchar](200) NULL,  // original data type

    ...

)

In my data table type, above, all of my types used to be nvarchar. When I changed the data types in the destination table to decimal(30, 15), I thought I could just change the data types in the corresponding user-defined table type to decimal as well, and that would force the data to be compatible. But my c# error trapping is still telling me "Error converting data type nvarchar to numeric.".

Any help would be appreciated.

To convert from nvarchar (string), you need to convert it, either in C# by doing double.Parse . If you want to keep it in your query, do:

select convert(decimal(4,2), '12.32')

...where you'd replace '12.32' with your column.

Be wary of how your decimals points are stored also. You may need to replace you local decimal point with the invariant one (replace ',' with '.').

If you want to change data types on insert, you can also do the same:

INSERT INTO CEDEN_ChemResults  (SampleData, EddName, InsertedAtUtc, NumericColumnA)
SELECT cr.SampleDate, @eddName, GETUTCDATE(), CONVERT(decimal(30,15), cr.OriginalVarcharColumn) FROM @chemResults cr

By passing the column names, you don't have to rely on columns having the same names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM