Showing posts with label insert. Show all posts
Showing posts with label insert. Show all posts

Friday, March 30, 2012

Id getting generated differently

Hi,

I created a PDA application with a database, which has a table with a uniqueidentifier field and primarykey.

While doing the bulk insert from dataset into sql mobile database, It is inserting the record but it is not inserting the id which was entered into the sql server 2005 database, instead the id by creating a new id and the code is as below.

conAdap = new SqlCeDataAdapter(strQuery, conSqlceConnection);

SqlCeCommandBuilder cmdBuilder = new SqlCeCommandBuilder(conAdap);

conAdap.Fill(dsData);

int r =conAdap.Update(dsData);

Please help me.

Thank you,

Prashant

Hi Prashant - I'm not sure I understand your issue. Could you explain in more detail and also give me somee information about the schema of the table itself? I'm interested in the list of columns, their types, PK, FKs, Indexes, and default values you have assigned on columns.

I'm also interested to know if the table is the product of an RDA pull with tracking on or merge replication article.

thanks,

Darren

ID for New record

Hi,
How can I insert a new record in sql table and retrun the ID of that reocrd using a stored procedure?
Thanks,From Books Online:

INSERT INTO jobs (job_desc,min_lvl,max_lvl)
VALUES ('Accountant',12,125)
SELECT @.@.IDENTITY AS 'Identity'

In stored proc:

create procedure sp_Test

@.outputvalue int output
as

INSERT INTO jobs (job_desc,min_lvl,max_lvl)
VALUES ('Accountant',12,125)
SELECT @.outputvalue = @.@.IDENTITY|||Thanks DMWCincy.|||Watch out fot @.@.IDENTITY, better use SCOPE_IDENTITY() besuase @.@.IDENTITY will return the last increment for the table, not necessarily the one that was generated by you transaction.

Id (indentity) is increments on faults.

Hi,

When i eg. manually ad entries to a table and, cancels the insert Ms SQL
increment the counter on the ID anyway. Is there a way to avoid this
behavior?

Regards
AndersFlare (dct_flare@.hotmail.com) writes:
> When i eg. manually ad entries to a table and, cancels the insert Ms SQL
> increment the counter on the ID anyway. Is there a way to avoid this
> behavior?

Yes, don't use the IDENTITY property, but roll your own. IDENTITY works
that way by design. By grabbing one number which never has to be
rolled back, insertions into tables with IDENTITY columns can scale
better.

One way to get a key on your on is:

BEGIN TRANSACTION

SELECT @.id = coalesce(MAX(id), 0) + 1 FROM tbl (UPDLOCK)

INSERT tbl (id, col1, col2, ...)
VALUES (@.id, @.par1, @.par2, ...)

COMMIT TRANSACTION

The UPDLOCK is required to avoid that two processes grab the
same id.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.aspsql

Friday, March 23, 2012

I want to set this error into a variable

hi all
Now I have an error operation, then SQL Server give error message as
follows:
Violation of UNIQUE KEY constraint 'gwbh'. Cannot insert duplicate key in
object 't_xt_gwsj'. "
I want to set this error into a variable, e.g. @.errstr
how to do?
thanks!
?Hi
http://www.sommarskog.se/error-handling-I.html
http://www.sommarskog.se/error-handling-II.html
"?" <zhangchao19@.hotmail.com> wrote in message
news:%237btgD$HGHA.3752@.TK2MSFTNGP11.phx.gbl...
> hi all
> Now I have an error operation, then SQL Server give error message as
> follows:
> Violation of UNIQUE KEY constraint 'gwbh'. Cannot insert duplicate key in
> object 't_xt_gwsj'. "
> I want to set this error into a variable, e.g. @.errstr
> how to do?
> thanks!
> --
> ?
>|||thank you very much, these articles is very helpful.
I also have a question, for example:
when @.error=111 , the corresponding string in table sysmessages is
" '%ls' must be the first statement in a query batch. " (mark as A)
and in query analyzer we may see :
" create procedure must be the first statement in a query batch. " (mark as
B)
In this case, "create procedure" is the run-time value of %ls.
Now, I want to know, Is it possible to get this run-time value diretly? As
example above,
Is it possible to get the value "create procedure" without comparing and
parsing
the origin message A and run-time string B.
thx again.
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:u21TIK$HGHA.3984@.TK2MSFTNGP14.phx.gbl...
> Hi
> http://www.sommarskog.se/error-handling-I.html
> http://www.sommarskog.se/error-handling-II.html
>
> "?" <zhangchao19@.hotmail.com> wrote in message
> news:%237btgD$HGHA.3752@.TK2MSFTNGP11.phx.gbl...
>|||There are some kind of errors that you will not be able to capture. Upgrade
to SQL Server 2005 and you will benefit from BEGIN TRY ..CATCH error handle.
BEGIN TRANSACTION
BEGIN TRY
INSERT Title VALUES (@.Title_ID, Title_Name, ' ', ' ', ' ', ' ', 1112, 0)
WAITFOR DELAY '00:00:05'
SELECT COUNT (*) FROM Authors
COMMIT
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ER_Num
ROLLBACK
END CATCH;
SELECT @.@.TRANCOUNT AS '@.@.TCount
"tamsun" <tamsun@.gmail.com> wrote in message
news:uOqivOAIGHA.3944@.tk2msftngp13.phx.gbl...
> thank you very much, these articles is very helpful.
> I also have a question, for example:
> when @.error=111 , the corresponding string in table sysmessages is
> " '%ls' must be the first statement in a query batch. " (mark as A)
> and in query analyzer we may see :
> " create procedure must be the first statement in a query batch. " (mark
> as B)
> In this case, "create procedure" is the run-time value of %ls.
> Now, I want to know, Is it possible to get this run-time value diretly? As
> example above,
> Is it possible to get the value "create procedure" without comparing and
> parsing
> the origin message A and run-time string B.
> thx again.
>
> "Uri Dimant" <urid@.iscar.co.il> wrote in message
> news:u21TIK$HGHA.3984@.TK2MSFTNGP14.phx.gbl...
>|||but only SQL Server 2000
?
"Uri Dimant" <urid@.iscar.co.il> д?
news:eakPiuAIGHA.3064@.TK2MSFTNGP10.phx.gbl...
> There are some kind of errors that you will not be able to capture.
Upgrade
> to SQL Server 2005 and you will benefit from BEGIN TRY ..CATCH error
handle.
> BEGIN TRANSACTION
> BEGIN TRY
> INSERT Title VALUES (@.Title_ID, Title_Name, ' ', ' ', ' ', ' ', 1112, 0)
> WAITFOR DELAY '00:00:05'
> SELECT COUNT (*) FROM Authors
> COMMIT
> END TRY
> BEGIN CATCH
> SELECT ERROR_NUMBER() AS ER_Num
> ROLLBACK
> END CATCH;
> SELECT @.@.TRANCOUNT AS '@.@.TCount
>
>
> "tamsun" <tamsun@.gmail.com> wrote in message
> news:uOqivOAIGHA.3944@.tk2msftngp13.phx.gbl...
(mark
As
>|||only SQL Server 2000
?
"Uri Dimant" <urid@.iscar.co.il> д?
news:eakPiuAIGHA.3064@.TK2MSFTNGP10.phx.gbl...
> There are some kind of errors that you will not be able to capture.
Upgrade
> to SQL Server 2005 and you will benefit from BEGIN TRY ..CATCH error
handle.
> BEGIN TRANSACTION
> BEGIN TRY
> INSERT Title VALUES (@.Title_ID, Title_Name, ' ', ' ', ' ', ' ', 1112, 0)
> WAITFOR DELAY '00:00:05'
> SELECT COUNT (*) FROM Authors
> COMMIT
> END TRY
> BEGIN CATCH
> SELECT ERROR_NUMBER() AS ER_Num
> ROLLBACK
> END CATCH;
> SELECT @.@.TRANCOUNT AS '@.@.TCount
>
>
> "tamsun" <tamsun@.gmail.com> wrote in message
> news:uOqivOAIGHA.3944@.tk2msftngp13.phx.gbl...
(mark
As
>

I want to see the actual SQL being passed - how?

I'm getting a "Input string was not in a correct format."when I'm running a insert statement against my SQL Server 2005 db table. This helps me zilch as I cant see the actual SQL statement to see which one wasnt right. Using a SQLDatasource and a Formview btw.

Datasource is called xSqlIB and formview is called fmvIB.

Any ideas?

synergy, have you tried running the profiler against your db and see what is trying to be executed vs the db? also, have you tried to step through to where the string is being created? if you have access to sql server mgt studio, just go to tools and select sql server profiler. then you can see the string that is getting executed...hope this helps -- jp|||

Synergyauto:

I'm getting a "Input string was not in a correct format."when I'm running a insert statement against my SQL Server 2005 db table. This helps me zilch as I cant see the actual SQL statement to see which one wasnt right. Using a SQLDatasource and a Formview btw.

Datasource is called xSqlIB and formview is called fmvIB.

Any ideas?

That error is not coming from SQL Server; it is coming from your .NET code. So it's not getting as far as the SQL Server and running Profiler will not be of much assistance to you.

|||nice call tmorton...|||

You can set up a function in the xSqlIB_Inserting function that will give you your insert statement, you can write a quick loop to write out all of your varialbes to trace and see what they are. Set tracing to true on your page, and all the information you want will show up at the bottom in red. Good luck!

ProtectedSub sqlProjectData_Inserting(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.SqlDataSourceCommandEventArgs)Handles sqlProjectData.InsertingTry

Trace.Warn(e.Command.CommandText)

Dim xAsInteger = 0DoUntil x = e.Command.Parameters.Count

Trace.Warn(e.Command.Parameters(x).ParameterName)

IfNot (e.Command.Parameters(x).ValueIsNothing)Then

Trace.Warn(e.Command.Parameters(x).Value.ToString)

EndIf

x += 1

LoopCatch exAs ExceptionDim oLoggerAsNew ErrorLogger.clsLogError(ex, Session, Request)

oLogger.LogError()

EndTryEndSub

|||

Unfortunately the page errors before xSqlIB_Inserting is ever called so that could isnt running (and I dont seem to have your ErrorLogger class). Trace function is nifty though and its cool to finally be able to see what the page sees so quickly. Here's a c/p of what the page shows in red. I dont see it showing me the actual db field that is freaking out on though:

Unhandled Execution Error
Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info)
at System.String.System.IConvertible.ToByte(IFormatProvider provider)
at System.Convert.ChangeType(Object value, TypeCode typeCode, IFormatProvider provider)
at System.Web.UI.WebControls.Parameter.GetValue(Object value, String defaultValue, TypeCode type, Boolean convertEmptyStringToNull, Boolean ignoreNullableTypeChanges)
at System.Web.UI.WebControls.Parameter.get_ParameterValue()
at System.Web.UI.WebControls.ParameterCollection.GetValues(HttpContext context, Control control)
at System.Web.UI.WebControls.SqlDataSourceView.InitializeParameters(DbCommand command, ParameterCollection parameters, IDictionary exclusionList)
at System.Web.UI.WebControls.SqlDataSourceView.ExecuteInsert(IDictionary values)
at System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback)
at System.Web.UI.WebControls.FormView.HandleInsert(String commandArg, Boolean causesValidation)
at System.Web.UI.WebControls.FormView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.WebControls.FormView.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.FormViewRow.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

|||Anyone home? hehe|||synergy, what is the number you are trying to convert. i see the parse int32 in the printout and what is the code trying to work with that number? - jp|||

jdingo:

synergy, what is the number you are trying to convert. i see the parse int32 in the printout and what is the code trying to work with that number? - jp

Here's the whole datasource from code, I'm not doing any code behind work on the datasource.

<asp:SqlDataSourceID="xSqlIB"runat="server"ConnectionString="<%$ ConnectionStrings:TestETSAppConnectionString %>"

DeleteCommand="DELETE FROM [xECSIBHeader] WHERE [IBHeaderKey] = @.IBHeaderKey"InsertCommand="INSERT INTO [xECSIBHeader] ([IBNumber], [IBTyp], [IBStatus], [CATCode], [Project], [SeverityCode], [CoverageFeeType], [DateClosed], [AdjusterID], [ClaimNumber], [PolicyNumber], [InsuredName], [Location01], [Location02], [City], [State], [ZipCode], [GrossLoss], [SalesTaxPercent], [SalesTaxAmount], [LossDate], [Supplement], [SupplementExplaination], [MultipleClaim], [ReBilled], [ReBilledIBSubmitted], [OriginalIBNumber], [OriginalIBFee], [RevenueAmtApplied], [ExpenseAmtApplied], [SalesTaxAmtApplied], [CommissionDocBal], [DocBal], [DocumentSelected], [CommissionStatus], [InvoiceStatus], [StatementID], [TaxGroup]) VALUES (@.IBNumber, @.IBTyp, @.IBStatus, @.CATCode, @.Project, @.SeverityCode, @.CoverageFeeType, @.DateClosed, @.AdjusterID, @.ClaimNumber, @.PolicyNumber, @.InsuredName, @.Location01, @.Location02, @.City, @.State, @.ZipCode, @.GrossLoss, @.SalesTaxPercent, @.SalesTaxAmount, @.LossDate, @.Supplement, @.SupplementExplaination, @.MultipleClaim, @.ReBilled, @.ReBilledIBSubmitted, @.OriginalIBNumber, @.OriginalIBFee, @.RevenueAmtApplied, @.ExpenseAmtApplied, @.SalesTaxAmtApplied, @.CommissionDocBal, @.DocBal, @.DocumentSelected, @.CommissionStatus, @.InvoiceStatus, @.StatementID, @.TaxGroup)"SelectCommand="xECS_sp_SelectIBDetails"SelectCommandType="StoredProcedure"UpdateCommand="UPDATE [xECSIBHeader] SET [IBNumber] = @.IBNumber, [IBTyp] = @.IBTyp, [IBStatus] = @.IBStatus, [CATCode] = @.CATCode, [Project] = @.Project, [SeverityCode] = @.SeverityCode, [CoverageFeeType] = @.CoverageFeeType, [DateClosed] = @.DateClosed, [AdjusterID] = @.AdjusterID, [ClaimNumber] = @.ClaimNumber, [PolicyNumber] = @.PolicyNumber, [InsuredName] = @.InsuredName, [Location01] = @.Location01, [Location02] = @.Location02, [City] = @.City, [State] = @.State, [ZipCode] = @.ZipCode, [GrossLoss] = @.GrossLoss, [SalesTaxPercent] = @.SalesTaxPercent, [SalesTaxAmount] = @.SalesTaxAmount, [LossDate] = @.LossDate, [Supplement] = @.Supplement, [SupplementExplaination] = @.SupplementExplaination, [MultipleClaim] = @.MultipleClaim, [ReBilled] = @.ReBilled, [ReBilledIBSubmitted] = @.ReBilledIBSubmitted, [OriginalIBNumber] = @.OriginalIBNumber, [OriginalIBFee] = @.OriginalIBFee, [RevenueAmtApplied] = @.RevenueAmtApplied, [ExpenseAmtApplied] = @.ExpenseAmtApplied, [SalesTaxAmtApplied] = @.SalesTaxAmtApplied, [CommissionDocBal] = @.CommissionDocBal, [DocBal] = @.DocBal, [DocumentSelected] = @.DocumentSelected, [CommissionStatus] = @.CommissionStatus, [InvoiceStatus] = @.InvoiceStatus, [StatementID] = @.StatementID, [TaxGroup] = @.TaxGroup WHERE [IBHeaderKey] = @.IBHeaderKey"><DeleteParameters><asp:ParameterName="IBHeaderKey"Type="Int64"/></DeleteParameters><UpdateParameters><asp:ParameterName="IBNumber"Type="String"/><asp:ParameterDefaultValue="R"Name="IBTyp"Type="Byte"/><asp:ParameterDefaultValue="1"Name="IBStatus"Type="Byte"/><asp:ParameterName="CATCode"Type="String"/><asp:ParameterDefaultValue="C002003"Name="Project"Type="String"/><asp:ParameterName="SeverityCode"Type="Int16"/><asp:ParameterDefaultValue="1"Name="CoverageFeeType"Type="Int16"/><asp:ParameterDefaultValue="1/1/1900"Name="DateClosed"Type="DateTime"/><asp:ParameterDefaultValue="271"Name="AdjusterID"Type="Int32"/><asp:ParameterName="ClaimNumber"Type="String"/><asp:ParameterName="PolicyNumber"Type="String"/><asp:ParameterName="InsuredName"Type="String"/><asp:ParameterName="Location01"Type="String"/><asp:ParameterName="Location02"Type="String"/><asp:ParameterName="City"Type="String"/><asp:ParameterName="State"Type="String"/><asp:ParameterName="ZipCode"Type="String"/><asp:ParameterDefaultValue="0.00"Name="GrossLoss"Type="Double"/><asp:ParameterDefaultValue="0"Name="SalesTaxPercent"Type="Double"/><asp:ParameterDefaultValue="0"Name="SalesTaxAmount"Type="Double"/><asp:ParameterDefaultValue="1/1/1900"Name="LossDate"Type="DateTime"/><asp:ParameterName="Supplement"Type="Boolean"/><asp:ParameterName="SupplementExplaination"Type="String"/><asp:ParameterName="MultipleClaim"Type="Boolean"/><asp:ParameterName="ReBilled"Type="Boolean"/><asp:ParameterName="ReBilledIBSubmitted"Type="Boolean"/><asp:ParameterName="OriginalIBNumber"Type="String"/><asp:ParameterName="OriginalIBFee"Type="Double"/><asp:ParameterName="RevenueAmtApplied"Type="Double"/><asp:ParameterName="ExpenseAmtApplied"Type="Double"/><asp:ParameterName="SalesTaxAmtApplied"Type="Double"/><asp:ParameterName="CommissionDocBal"Type="Double"/><asp:ParameterName="DocBal"Type="Double"/><asp:ParameterName="DocumentSelected"Type="Boolean"/><asp:ParameterName="CommissionStatus"Type="Int16"/><asp:ParameterName="InvoiceStatus"Type="Int16"/><asp:ParameterName="StatementID"Type="Int32"/><asp:ParameterName="TaxGroup"Type="String"/><asp:ParameterName="IBHeaderKey"Type="Int64"/></UpdateParameters><SelectParameters><asp:QueryStringParameterDefaultValue="18R315973"Name="ClaimNumber"QueryStringField="ClaimNumber"Type="String"/></SelectParameters><InsertParameters><asp:ParameterName="IBNumber"Type="String"/><asp:ParameterDefaultValue="R"Name="IBTyp"Type="Byte"/><asp:ParameterDefaultValue="3"Name="IBStatus"Type="Byte"/><asp:ParameterName="CATCode"Type="String"/><asp:ParameterDefaultValue="C002003"Name="Project"Type="String"/><asp:ParameterName="SeverityCode"Type="Int16"/><asp:ParameterDefaultValue="1"Name="CoverageFeeType"Type="Int16"/><asp:ParameterDefaultValue="1/1/1900"Name="DateClosed"Type="DateTime"/><asp:ParameterDefaultValue="271"Name="AdjusterID"Type="Int32"/><asp:ParameterName="ClaimNumber"Type="String"/><asp:ParameterName="PolicyNumber"Type="String"/><asp:ParameterName="InsuredName"Type="String"/><asp:ParameterName="Location01"Type="String"/><asp:ParameterName="Location02"Type="String"/><asp:ParameterName="City"Type="String"/><asp:ParameterName="State"Type="String"/><asp:ParameterName="ZipCode"Type="String"/><asp:ParameterDefaultValue="0.00"Name="GrossLoss"Type="Double"/><asp:ParameterDefaultValue="0"Name="SalesTaxPercent"Type="Double"/><asp:ParameterDefaultValue="0"Name="SalesTaxAmount"Type="Double"/><asp:ParameterDefaultValue="1/1/1900"Name="LossDate"Type="DateTime"/><asp:ParameterName="Supplement"Type="Boolean"/><asp:ParameterName="SupplementExplaination"Type="String"/><asp:ParameterName="MultipleClaim"Type="Boolean"/><asp:ParameterName="ReBilled"Type="Boolean"/><asp:ParameterName="ReBilledIBSubmitted"Type="Boolean"/><asp:ParameterName="OriginalIBNumber"Type="String"/><asp:ParameterName="OriginalIBFee"Type="Double"/><asp:ParameterName="RevenueAmtApplied"Type="Double"/><asp:ParameterName="ExpenseAmtApplied"Type="Double"/><asp:ParameterName="SalesTaxAmtApplied"Type="Double"/><asp:ParameterName="CommissionDocBal"Type="Double"/><asp:ParameterName="DocBal"Type="Double"/><asp:ParameterName="DocumentSelected"Type="Boolean"/><asp:ParameterName="CommissionStatus"Type="Int16"/><asp:ParameterName="InvoiceStatus"Type="Int16"/><asp:ParameterName="StatementID"Type="Int32"/><asp:ParameterName="TaxGroup"Type="String"/></InsertParameters></asp:SqlDataSource>|||

Dang, sorry, guess i hit "post" 3 times too many

________________________________________________________________

Note: duplicate posts were deleted by moderator tmorton

|||synergy, i dont have an exact answer from what i have seen, but if you are getting no where and i know you have lots of fields you are working with, but you could run your insert command trying each field at a time and see which one throws the error in case it is a simple matter some mismatch between and accepted value for a field in the DB and an actual value being passed in as a parameter. I know it is a more brute force approach but thats all i have at the moment. good luck -- jp|||Thanks for hanging with me jdingo, I noticed in the code above that 2 fields were listed as "byte" (dunno how it got that way) but they were really integer fields. So passing them "False" instead of an integer was causing the error. Thanks for the help!|||nice synergy, glad that you found it, many times i solve my own problems just by explaining them and going through them with others. have a good one-- jpsql

Friday, March 9, 2012

I Need Your Help,About SQL2000 DataInsert

I want to insert some data into my SQLServer,For example:insert into xcjl(zch,xcsj) values('027741',getdate())

but ,the "zch" maybe have a few data,I want to insert these step by step,how can I do?

Can you explain in more detail what you are trying to accomplish?

I need to speed this process up

I need to speed this process up.
Insert into dbo.temp_table
(record_number, etc...)
select record_number, etc...
from
dbo.incoming_temp
set Indentity _insert temp_table on
It's about 10 million records and usally runs 2-3 hours. Any ideas?????Break it up int to 10 separate transaction?|||You mean like 2 million record at a time.
Select yadA, YADA YADA,
YADA, YADA, YADO
FROM YADA
WHERE RECORD_id < 2000000

SOMETHING LIKE THAT|||Something like?

DECLARE @.x int, @.y int

SELECT @.x=0, @.y = SELECT COUNT(*) FROM myTable99

WHILE @.X < @.y
BEGIN
BEGIN TRAN
INSERT...
COMMIT TRAN
SELECT @.x = @.x + 2000000
END|||thanks, this gave me some insight on how to structure other thing with my group,.|||Let us know if it helps...

Also Don't forget the last set of records...

You may fall out of the loop before everything is done...

Do

WHERE Record_ID > @.x|||Look for nonlogged operations in BOL. Try "select into" to avoid logging.|||Breaking the insert will not speed up the completion of the entire batch. Either SELECT * INTO... or bulk copy utility (BCP/BULK INSERT)|||The fastest possible speed you can get is:

1. Use BCP.
2. Set your recovery mode to Bulk-logged or simple while you do the operation.

Also, how long is your SELECT taking? If the length is in the select, these ideas aren't going to do you a lot of good.|||Bulk-logged will defeat the purpose of using BCP/BULK INSERT because it will log those operations, as opposed to Simple which will not.

Even if SELECT is slow, non-logged operations would still buy you some advantage over INSERT, which is logged (unless you set recovery mode to Bulk-Logged, in which case it would be a wash ;))|||The logging on bcp, bulk insert, INSERT INTO, CREATE INDEX, text and image manipulations are kept to a minimum when using bulk-logged and it performs faster than full recovery mode, while still providing a level of protection to your other transactions. It is actually quite a bit faster on really large bulk operations.

I agree with the second part, except for the part in ().|||Breaking the insert will not speed up the completion of the entire batch. Either SELECT * INTO... or bulk copy utility (BCP/BULK INSERT)

I mean bcp is the way to go...but if you break up the work into chunks you will notice a difference...

What'dya think the log will look like?

What'dya think it'd be like if he had to roll the whole thing back...|||Bulk-logged "permits high-performance bulk copy operations", but does alow for other DDL/DML to be logged. If data recovery is important while performing the process at hand, then Bulk-logged is the one to use. Else, - Simple will be just fine.

Brett, I don't think you can roll back a bulk copy operation. Do you know the way? On either BCP or BULK INSERT you can specify the number of records to be viewed as transaction. This way there is not need to break anything up.|||Someone tell me why BCP is faster than a non-logged insert. Is it just because there is minimal data checking and verification? It doesn't make sense to me that spitting everything out to disk and then reading it in again would be particularly fast.|||derrickleggett is right, and using bulk copy utility is not the same as selecting or inserting. it is a much more efficient operation for large volumes of data.|||Still long on repetition, short on substance...|||BCP/BULK INSERT may not necessarily be faster than non-logged insert. The discussion started with how to introduce transactional control while handling large amounts of data. In addition, you do not need to drop the table every time you need to populate it AGAIN, if you choose to use BCP or BULK INSERT, as opposed to SELECT...INTO...FROM.|||Good enough for me.|||Oye...

First: Non-Logged is a misnomer...everything, and I mean everything, that is a database transaction, is logged...it's a matter of at what level...

I don't think bcp out is logged...so there's a savings...

bcp in must be logged, at the page level, just like BULK INSERT...

Or SELECT * INTO

If they fail, for ANY reason, it WILL rolback

And I question how the original table gets populated....|||Hmmm, never tried to force a BCP to fail in the middle of the load, but I'll guess that if you unplug your cat-5 while it's posting records, - at a minimum you'll get a partial load, at a maximum corrupted table. I don't think it'll roll back. But then again, as I said - never tried it, so go easy if you prove me wrong ;)|||I need to speed this process up.

Insert into dbo.temp_table
(record_number, etc...)
select record_number, etc...
from
dbo.incoming_temp
set Indentity _insert temp_table on

It's about 10 million records and usally runs 2-3 hours. Any ideas?????

Locate the filegroups for dbo.temp_table and for dbo.incoming_temp on seperate dedicated physical disks.|||I haven't even used BCP for a long time, but I seem to recall it loading data in distinct batches, hence the batch size parameter.

Yeah, I'd be interested in seeing if it rolled back if the process got interupted. This sounds like a call to Super-Brett to me.|||This is a very good response. I think the bcp utility might be the best course of action. Again, this table hold aproximately 10,000,000 records which represent 6 months historical data. That has been pulled out of the primary table that hold 290,000,000 records that have never been purged. The strucktures are the same. I just need to truncate the primary table and pull in my 10,000 records. When I attempted a straight
Insert into table
(1,2,3,4etc.......
selecte 1,2,3,4etc.....
from primary table.
it run a-round three hours and the tranaction log grows as large as the data file. Besides it bomb after three hour yesterday. Do you agree with my plan??|||I haven't even used BCP for a long time, but I seem to recall it loading data in distinct batches, hence the batch size parameter.
BCP and BULK INSERT load data in distinct batches, but it's independent of batch size parameter. A switch "-b" specifies how many rows should be loaded at a time before a COMMIT gets issued. It has nothing to do what you see on the output of BCP or BULK INSERT.|||This is what I came up with so far.

bulk insert websense.dbo.[temp_table]
FROM websense.dbo.[incoming_temp]
-b = 100,000

I want to insert commit 100,00 records at a time.|||First you BCP...OUT from the source table into a host file (BCP utility terminology, means a text file). While forming the command, make sure to specify AND REMEMBER whether you're going to use character "-c" or native "-n" file format.

Then, in QA, type your statement:

bulk insert websense.dbo.[temp_table]
FROM '<path_to_your_source_file>'
WITH (ROWS_PER_BATCH = 100000, DATAFILETYPE = 'char')

If your BCP was using "-n" then instead of 'char' you'll need 'native' for FORMATFILE parameter in BULK INSERT.|||bulk insert websense.dbo.[temp_table]
FROM '<websens.dbo.[incoming_temp]>
WITH (ROWS_PER_BATCH = 100000)|||If your BCP was using "-n" then instead of 'char' you'll need 'native' for FORMATFILE parameter in BULK INSERT.
It should be DATAFILETYPE instead of FORMATFILE. That's what copy-paste does to me :o|||I haven't even used BCP for a long time, but I seem to recall it loading data in distinct batches, hence the batch size parameter.

Yeah, I'd be interested in seeing if it rolled back if the process got interupted. This sounds like a call to Super-Brett to me.

WHAT?

Why not?

DTS?

No thanks...

The pages are logged on the BCP in...without the batch it will roll the whole thing...page by page, back...not at the row level...

Instead of guessing, can you tell us what the process you are really trying to accomplish is?

It's not often that there's a need to move 10 million around in 1 shot...

What's up?|||DTS sucks. I'd still use BCP over it whenever possible, but these days a lot of requirements specify DTS, and frankly for the past few years I've mostly worked on virgin data entry systems that haven't needed much bulk-loaded data.|||I've mostly worked on virgin data entry systems

Dude, leave those high school girls alone....|||Dude, leave those high school girls alone....High school? You really have been "out of the loop" for a while, haven't you ?!?!

Try grade school. There might be some left there!

-PatP|||It this some new code I'm not aware of?LOL. I get it. It's a way to keeps things relavent. Like a good politian huh.|||It this some new code I'm not aware of?LOL. I get it. It's a way to keeps things relavent. Like a good politian huh.
It's been a rough weekend, hey? :D|||High school? You really have been "out of the loop" for a while, haven't you ?!?!

Try grade school. There might be some left there!

-PatP

Well it sounds like that process has sped up...

Damn...now I gotta buy a shotgun...

Wednesday, March 7, 2012

I need SQL Query Help

Sir,

We are try to insert query like this

Insert into Table_1 (smDate,Description) Values ('Thu, Feb 15, 2007 03:00 PM', ' Hai, It's Just for Testing')

This is Exact Query about this...

We know about MS ACCESS it has Built in function like Format('Thu, Feb 15, 2007 03:00 PM','mm/dd/yyyy HH:MM')

But I am new to SQL. I dont know the The Date Format built in function in SQL Server.

How can i Insert this Quesry to SQL Table

and also How can insert "it's " this type of words into SQL..

Can you help me

this is very helpful for my project

Thanks With Regards

S.Senthil Nathan

The quickest way i've used and seen being used to put an apostrophe into a SQL statment, is to do a replace on the string with a double quote, then you will need to do a reverse replace on the double quote back to an apostrophe, not the best way but one solution, the other is to escape the apostrophe with another so it would beit''sbut this would still require some parsing of the string.

Have a look at this artilce for working with formatting the date/time in SQL :http://sqljunkies.com/Article/6676BEAE-1967-402D-9578-9A1C7FD826E5.scuk

|||

For your date format issue, if you can remove the "Day, " from the date, you can insert the string you have. I.e. 'Feb 15, 2007 3:00 PM' is a valid date string and will be formatted automatically by SQL server according to how SQL server is set up. For example, if using the defaults on a US-based setup, SQL server formats the date like you requested.

if you need to insert something with single quotes, you have two options. First, you can replace it with two single quotes, i.e. 'it''s' would putit's in the database.

Second, you can use parameters. Your sql statement would be like "INSERT INTO dbo.MyTable (StringValue) Values (@.StringValue)", and then add a sql parameter to your sqlcommand as if you were using a stored procedure. If you had a Data.SqlClient.SqlCommand named command:

command.CommandType = Data.CommandType.Textcommand.CommandText = strSQL' this is your insert statement with a parametercommand.Parameters.AddWithValue("@.StringValue", "it's")
I prefer the second choice becuase it's easier than remembering to replace quotes and other sql syntax.

I need SQL Query Help

Sir,

We are try to insert query like this

Insert into Table_1 (smDate,Description) Values ('Thu, Feb 15, 2007 03:00 PM', ' Hai, It's Just for Testing')

This is Exact Query about this...

We know about MS ACCESS it has Built in function like Format('Thu, Feb 15, 2007 03:00 PM','mm/dd/yyyy HH:MM')

But I am new to SQL. I dont know the The Date Format built in function in SQL Server.

How can i Insert this Quesry to SQL Table

and also How can insert "it's " this type of words into SQL..

Can you help me

this is very helpful for my project

Thanks With Regards

S.Senthil Nathan

Senthil:

look up CAST AND CONVERT under CONVERT in books online to get a look at date and time formats. The ISO format is format 112. This should get you moving in the right direction.


Dave

|||Hi,

convertion was already explained by another posted, the issue with the quotes can be solved using two single quotes instead of one.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de

Sunday, February 19, 2012

I need help with an insert clause, please help

I am trying to write a complex insert statement and not really sure how to get started.

First I am building an application to a record label to add artist, songs, pictures, video, and music to their site.

Thanks to asp.net 2.0 building the application interface was easy, but now I realize I have run into a brick wall and need some help.

in one application, called "add artist album"

in this application, you, the website administrator, are adding information to two different tables (artist (holds all info about the artist), album (holds all the info about artist album))

I have no clue how to really start writing an insert statement for this.

Basically I want to be able to insert the album data (artistid (foreign key), album name and release date) and also have a drop down listbox, which is connected to the database by the sqldatasource connector to allow the administrator to choose an artist from the artist table so that when they add the albem and release date they, the administrator, can choose which artist in the drop down list box to associate with the album and release date data that goes in the album table. That association is made with the artistid because it is a foreign key to the artist table but how do I insert the chosen artistid number into that foreign key field for the album table?


Please can someone point me in the right direction.

I am thinking that the insert statement will be something like and insert with nested select statement and inner join included but i haven't a clue how to do this.

My table DDL

Create table artist (artistid int prmrykey, artistname varchar (100), bio varchar(100))

Create table album (albumid int prmrykey, albumname varchar (100), releasedate date, artistid int foreignkey)

My DML for the insert statement so far:

ALTER PROCEDURE sp_AddArtistAlbum
@.AlbumName varchar(50),
@.ReleasedDate datetime,
@.ArtistID int
AS

SET NOCOUNT ON

DECLARE@.AlbumIDINTINSERT INTOtb_Album

(AlbumName, ReleasedDate, ArtistID)

VALUES(@.AlbumName, @.ReleasedDate,selectArtistIDfromtb_ArtistwhereArtistID = (ArtistID from sqldatasource from the drop down listbox) )

Like I said know I am supposed to have a select subquery statement that is nested to really make this thing work but I do not know where to start, can someone please help me.

I hope I have provided enough information.

My expected results are to insert data from into the album table and have that data associated with an artist chosen in the drop down box.

Please Help!!!!!!!!!!!!!!

ALTER PROCEDUREsp_AddArtistAlbum@.AlbumNamevarchar(50),@.ReleasedDatedatetime,@.ArtistIDintASSET NOCOUNT ONDECLARE @.AlbumIDINTINSERT INTO tb_Album(AlbumName, ReleasedDate, ArtistID)VALUES (@.AlbumName, @.ReleasedDate, @.ArtistID)

The ArtistID is the SelectedValue from your DropDownList (althought the Artist Name appears in the dropdown). That's all you need to insert. It's there and available without any additional messing about.

If you look at the logic of your proposed SQL, you will see that it says "I have the ArtistID from the dropdown, Now I want to select the ArtistID from the Artist table that matches the ID I already have". Bit of a nonsense when you analyse it like that...Big Smile