Showing posts with label created. Show all posts
Showing posts with label created. Show all posts

Friday, March 30, 2012

Inserting .doc data into varbinary column

I need to put .doc data into a varbinary column for full text searching. I have created the db and columns but am unsure as to how to insert the varbinary data. I have found some discussions about inserting images but nothing explicitly on .doc files. Can anyone suggest resources or sample code?

The varbinary datatype does not differentiate the contents of the field, it's all just binary data as far as SQL is concerned. The samples you've found for images should apply equally to any type of binary object, it just seems that most examples are focues on image since most people want to store image data.

Mike

|||Thanks Mike. I will try those examples.

Monday, March 26, 2012

Insert, Update & Delete on two tables with same data structure...

I have created two table with same data structure. I need realtime effects (i.e. data) on both tables - Table1 & Table2.

Following Points to Consider.

1. Both tables are in the same database.

2. Table1 is using for data entry & I wants the same data in the Table2.

3. If any row insert, update & delete occers on Table1, the same effect should be done on Table2.

4. I need real time data insert, update & delete on Table2.

I knew that using triggers it could be possible, I have successfully created a trigger for inserting new rows (using logical table "Inserted") in Table2 but not succeed for update & delete yet.

I want to understand how can I impletement this successfully without any ambiguity.

I have attached data structure for tables. Thanx...You want TWO tables with IDENTICAL structure and the SAME data in a SINGLE database?
We can help you debug your triggers if you post the code, but WHY?|||Actually we required some reports and as we have old version application, it could not be possible to generate required reports.

The data is dynamic (i.e. Table1) & changing with the stock quantity IN & OUT, thats why I will store data for specific span of time in the new table (Table2). I will use that data for reporting.

Which code you required..? I have attached script for creating a tables.|||I understand you want inserts copied to the second table.
What about updates? Do you want the data in the second table updated, or do you want a new record added instead?
What about deletes? Do you want the data in the second table deleted as well, or do you just want to mark the record as deleted?

Did you try writing triggers for Update and Delete? If so, post the code for those triggers and we will help you debug it our fix syntax errors.|||oye...redundant data...

In any case if you follow the Hint link sticky at the top of the forum and post what it tells you, I'm sure we can supply enough rope|||As I have told that the data entry done through frontend, I want each and every effect (i.e. row insert, update or delete) on Table2.

As I have told you that the second table I am using for reporting purpose & the reports will be wrong if it is not reflect the data which entered or modified last.

May be you think its too cumbersome but now let me explain the full scenario.

1. I have to do this because I have added new column in the Table2 which is not part of Table1.

2. Using insert trigger on Table1 I can add new row in Table2 same as Table1 as well as I can feed data in the new added column which is not part of Table1.

3. Whenever row inserted, update or delete in Table1 the Table2 should update accordingly.

4. I can not cascade update or delete because both tables are having only foreign keys. (cFinYrs, cLocCode, cMonth, cItemCode are foreign keys)

5. I will re-write triggers according to my requirement, but I need little help to be clear of the concept from you expert guys.

6. The script which I have given for creating a tables will create the same data structure for tables.

I have written trigger for insert, it's given below. It's working good for insert.

CREATE TRIGGER [InForRpt] ON [dbo].[Table1]
FOR INSERT

AS

Declare @.cFinYrs varchar(3)
Declare @.cLocCode varchar(7)
Declare @.cMonth varchar(3)
Declare @.iSrNo int
Declare @.cItemCode varchar(20)
Declare @.dQty dec
Declare @.dRate dec(9,2)
Declare @.cDesc varchar(200)
Declare @.cCreated varchar(6)
Declare @.dtcreated datetime
Declare @.cModified varchar(6)
Declare @.dtModified datetime
Declare @.cMachIP varchar(15)

SET @.cFinYrs = (select cFinYrs from inserted)
SET @.cLocCode = (select cLocCode from inserted)
SET @.cMonth = (select cMonth from inserted)
SET @.iSrNo = (select iSrNo from inserted)
SET @.cItemCode = (select cItemCode from inserted)
SET @.dQty = (select dQty from inserted)
SET @.cDesc = (select cDesc from inserted)
SET @.cCreated = (select cCreated from inserted)
SET @.dtcreated = (select dtCreated from inserted)
SET @.cModified = (select cModified from inserted)
SET @.dtModified = (select dtModified from inserted)
SET @.cMachIP = (select cMachIP from inserted)

Select @.dRate = drate from ssstockmst where citemcode=@.cItemCode

Insert INTO Table2 values(@.cFinYrs, @.cLocCode, @.cMonth,
@.iSrNo, @.cItemCode, @.dQty,
@.dRate, @.cDesc, @.cCreated,
@.dtCreated, @.cModified,
@.dtModified, @.cMachIP)

How I can make this happen..? Thanx for replying...|||oye...redundant data...

Yeah it could be redundant data but it will helps me lot to produce reports according to management requirement. And this data will not be heavy in size (1 to 5MB) so don't affect the server space as we have provision for same. :)|||I have to do this because I have added new column in the Table2 which is not part of Table1.This still makes no sense. Why not just add the column to Table1? Are you dealing with a reduced record set in table2? Is that data truncated occasionally, or filtered? We need to know how that data is being retained before helping you create Update/Delete triggers.

But regarding your insert trigger...

The method you have chosen is not only slow and verbose, but will also fail if more than one record is inserted into the table by a single transaction. Triggers MUST be designed to function correctly with multi-record inserts.

No exceptions.

This is the method you want to use for your insert trigger:CREATE TRIGGER [InForRpt] ON [dbo].[Table1]
FOR INSERT

AS
begin
insert into Table2
(cFinYrs,
cLocCode,
cMonth,
iSrNo,
cItemCode,
dQty,
dRate,
cDesc,
cCreated,
dtCreated,
cModified,
dtModified,
cMachIP)
select inserted.cFinYrs,
inserted.cLocCode,
inserted.cMonth,
inserted.iSrNo,
inserted.cItemCode,
inserted.dQty,
ssstockmst.dRate,
inserted.cDesc,
inserted.cCreated,
inserted.dtCreated,
inserted.cModified,
inserted.dtModified,
inserted.cMachIP
from inserted
left outer join ssstockmst on inserted.cItemCode = ssstockmst.cItemCode
endMuch simpler, eh?
Now, I really recommend that you go back to Books Online and read the sections on triggers, paying careful attention to the examples given.|||This still makes no sense. Why not just add the column to Table1? Are you dealing with a reduced record set in table2? Is that data truncated occasionally, or filtered? We need to know how that data is being retained before helping you create Update/Delete triggers.

I thought to add new column in the Table1 but Table1 is being used & lots of data in the table1. Second thing, I have to think of the forntend application too.

We found best solution for a while is to create a new table for same & we will update the table1 later, when we upgrade our database & application.

No, data is truncated...

Thanx blindman, for simplify insert trigger...|||I thought to add new column in the Table1 but Table1 is being used & lots of data in the table1. Second thing, I have to think of the forntend application too.Still makes no sense. You're taking up extra space by storing redundant data in table2, extra processing time by keeping the data synchronized, extra development time in setting up this process, and a properly designed front-end won't care or even know that you've added an extra column to the table.
You need a DBA to help you with this project...|||I have solved the problem.

1. I have created a surrogate key (combination of cFinYrs, cLocCode, cMonth & cItemCode) on Table1 and accordingly foreign key on Table2.

2. Set cascade for update & delete.

I have test it, it's working fine.

I am understanding what you want to say but right now I am not allowed to modify working table's structure. Surely I will do it but later.

Thanx blindman for all efforts you placed...

insert values into both table at the same time using sql server 2005

hi all,

In sql server 2005 i had created 2 tables,table 1 and table 2. Here is the detail of the table.

table 1:

tid--> int,identity,primary key

tname-->varchar(200)

table 2:

sid-->int,identity,primary key

tid-->fk (this tid is set as foreign key for the tid in table1)

now when i'm inserting values into tname i have to insert the value of tid from table 1 into the tid of table 2 both at the same time. any one know how this is possible? if so please send me the code..

pls help me..

thanks

swapna

Go For Stored Procedure for Insert...


SP Flow should be-

1. Start SQL Transaction

2. Insert into Table1

3. Get the Inserted INDENTITY value.

4.Insert into table 2

5. Commit Transaction Or Rollback transaction depending on the Error .

|||

You can create a stored procedure. There use will insert the record in the table 1 first and fetch the latest generated id value in table 1 using scope_identity and store it in a variable. Then you will insert the corresponding record in table 2 using the variable value.

For help on how to call a stored procedure from code visit http://forums.asp.net/t/1165758.aspx.

Feel free to ask for more help on this issue.

|||

Or you can create a trigger to insert the row into the second table.

It if must always happen the same way, the trigger would be a safer bet.

check out create trigger in the documentation.

sql

Wednesday, March 21, 2012

insert tmpTable vs Table

Is there a difference between inserting data into a temp table vs a real
table? I'm using an SP and I created a temp table. Then tried to INSERT and
failed. Then, for troubleshooting, I created a real table and INSERT works
fine. What characteristic about temp tables am I missing?
Both tables exist and I do a SELECT * on both. But only the real table has
records.
thanks
CREATE PROCEDURE stp_DOD_TrackNumbers
@.PID int, @.SK int, @.IDD int
AS
--if exists (select * from dbo.sysobjects where id =
object_id(N'[#tmpDODSongs]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
--drop table [#tmpDODSongs]
--CREATE TABLE [#tmpDODSongs] (
-- [ProjectID] [numeric](18, 0) NOT NULL ,
-- [SortKey] [numeric](18, 0) NULL ,
-- [OldIDD] [numeric](18, 0) NULL ,
-- [ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL
--) ON [PRIMARY]
INSERT INTO #tmpDODSongs (ProjectID, SortKey, OldIDD)
VALUES (@.PID, @.SK, @.IDD)
--INSERT INTO tmpDODSongs (ProjectID, SortKey, OldIDD)
--VALUES (@.PID, @.SK, @.IDD)
-- perform other tasks here before dropping temp table
--drop table [#tmpDODSongs]
GO> Then tried to INSERT and failed.
Could you be a bit more specific?|||I created a temp table #tmpDODSongs and logical table tmpDODSongs.
Both with the same attributes, structure, etc.
Using the same 17 records...
I could INSERT INTO the logical table tmpDODSongs with no problem.
When I tried to INSERT INTO temp table #tmpDODSongs - no records were
inserted.
I did not get any errors, just no inserted recods.
I used the same SP and would comment out one INSERT statement of the other.
I was just wondering if there was a consideration I needed to make for temp
tables.
thanks
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:%23nGpR766FHA.1188@.TK2MSFTNGP12.phx.gbl...
> Could you be a bit more specific?
>|||Where in the process is the select from the table?
shank wrote:
> Is there a difference between inserting data into a temp table vs a real
> table? I'm using an SP and I created a temp table. Then tried to INSERT an
d
> failed. Then, for troubleshooting, I created a real table and INSERT works
> fine. What characteristic about temp tables am I missing?
> Both tables exist and I do a SELECT * on both. But only the real table has
> records.
> thanks
> CREATE PROCEDURE stp_DOD_TrackNumbers
> @.PID int, @.SK int, @.IDD int
> AS
> --if exists (select * from dbo.sysobjects where id =
> object_id(N'[#tmpDODSongs]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
> --drop table [#tmpDODSongs]
> --CREATE TABLE [#tmpDODSongs] (
> -- [ProjectID] [numeric](18, 0) NOT NULL ,
> -- [SortKey] [numeric](18, 0) NULL ,
> -- [OldIDD] [numeric](18, 0) NULL ,
> -- [ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL
> --) ON [PRIMARY]
>
> INSERT INTO #tmpDODSongs (ProjectID, SortKey, OldIDD)
> VALUES (@.PID, @.SK, @.IDD)
> --INSERT INTO tmpDODSongs (ProjectID, SortKey, OldIDD)
> --VALUES (@.PID, @.SK, @.IDD)
>
> -- perform other tasks here before dropping temp table
> --drop table [#tmpDODSongs]
> GO
>|||I'm using QA to select the tracks from each table for the sake of
troubleshooting.
SELECT *
FROM #tmpDODSongs
SELECT *
FROM tmpDODSongs
thanks
"Trey Walpole" <treypole@.newsgroups.nospam> wrote in message
news:e25lJP76FHA.636@.TK2MSFTNGP10.phx.gbl...
> Where in the process is the select from the table?
> shank wrote:|||"shank" <shank@.tampabay.rr.com> wrote in
news:#nx8da76FHA.3752@.tk2msftngp13.phx.gbl:
> I'm using QA to select the tracks from each table for the sake of
> troubleshooting.
> SELECT *
> FROM #tmpDODSongs
[snip]
[snip]
Well, as per the code above, you drop the temp table - so if you try to
select out of it afterwards, you wouldn't get any data - would you?
Niels

Insert timeout on test db

I created a new test database on my database server using a daily backup of the live database. I did an structure and data compare and it is identical. From looking at the permissions it looks identical too. the problem is when I run an update proc the database connection times out. Ive changed the connection string to use the sa login and is still timesout. Ive also tested it by changing the database name to the live db and it works fine then. I must be missing something. Ive also tried to run "Exec sp_change_users_login 'auto_fix', 'sa' to see if it would work but nothing. The select statements seem to work though. Thanks for nay help in advance!

RyanCan we see the code and the exact error message?|||Have you tried executing the update manually? Also, you might want to update the timeout on the sql command to something longer, and see if it works.|||Instead of using the stored procedure I tried to execute a single update statement using c# code and the same one using query analyzer. The query analyzer one worked fine everytime with 2 different update statements but the code timed out on one. Both were just updating one field in one record. Both tables have triggers going on to, but Im using the same admin password in the code as Im using to login with query analyzer. The only other difference is that some stored procedures are encrypted and some are not But Im not sure all the procs and tables the triggers handle. I figured that wouldnt matter since im using an admin password. Does anyone know what is going on? Thanks

Ryan|||

ryanoc:

Does anyone know what is going on?


Not without seeing your code, no.|||The first update will always timeout, but the second one wont. Also, I created a database locally and restored it using the same file as the one im having problems with and I now have no timeout issues. ahhh!

//SqlConnection connRDK = new SqlConnection("Server=my_server;Database=ad_xx_beta;Persist Security Info=False;user id=sa;Password=xxx");


String sql;

sql = "UPDATE VHSLSFIN SET AmtPriceVehicle = '116907' WHERE SlsId = 'V01001878'";
//sql = "UPDATE COEMP SET NameNick = 'Ryan C' WHERE empid = '163'";

try
{

SqlCommand commRDK = new SqlCommand(sql, connRDK);

connRDK.Open();
commRDK.ExecuteNonQuery();
}
catch (Exception ex)
{
string x = (ex.Message);
}
finally
{
//done
}|||I think your catch statement is "swallowing" any exceptions you are receiving. What are you doing with the string x? Are you displaying it anywhere?|||Not using it anywhere except in debug mode to view the exeption which is allway server timeout on one of the queries|||

You can check the log file of the database to see whether it is always full

|||Where do I find it? What does full mean?|||

ryanoc:

Where do I find it? What does full mean?

Open your database because the Taskpad is context sensitive click on view at the top of Management Studio and you will see the Taskpad, click on it and you will see all the file allocation of the open database. You can increase the file size by changing from your existing size to something bigger. Hope this helps.

|||There is a big difference in the databases in question.

Live database with no timeouts:
allocated: 12.37mb
used: 3mb
free: 9.3mb

Test database with some timouts:
allocated: .99mb
used: .49mb
free: .5mb

Does this major difference have to do with my timeout problem? If so, how do I increase the transaction log for the test database? thanks very much!

Ryan|||I increased the size and still get the timeout :(|||

Try increasing both files the MDF(Microsoft data file) and the LDF(log data file) by changing the size of the files. Hope this helps.

|||Its the same as the other files. One other thing I noticed is that my database was created using my username, but the other database was created using the admin username.

Monday, March 19, 2012

Insert Time into SQL server

Hi,

I have created a wizard form to collect user information.When use click Finish button all the details added to the SQL server database.
That part is ok.
But my problem is this

Through my interface I am giving user to select the date and time.
(I have used AJAX datepicker and MaskedEdit control)

After user type the date (Normal format is - HH:MM:SS) and click finish button I check the database.

It automatically Inserted the date also (Jan 1 1900)

So I dont want this date part and I just want Time only.How do I do this ??

(I have used datatype as : nvarchar instead of datetime .Because of if i use datatime it automatically inserts both data and time values)

Values with thedatetimedata type are stored internally by Microsoft SQL Server as two 4-byte integers. The first 4 bytes store the number of days before or after thebase date, January 1, 1900. The base date is the system reference date. Values fordatetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight.

So in your case the first 4 bytes are not used. By default the value of Jan 1 1900 is displayed.

I do suggest that you continue to use the datetime value to store your time for filtering and sorting purposes but when you display the data to the end user you simply format the data to a time format.

Hope this helps!

|||

Hi,

you can convert your datetime with the CONVERT command, e.g. (in Query Analyzer):

Declare @.input As DateTime
Set @.input = Getdate()

Select Convert(nvarchar,@.input,108)

Regards
Marc André

|||

Hi,

thanks for your reply.Smile

Wednesday, March 7, 2012

INSERT Records in multiple tables

I need to update two tables. I have created a view and am using the code in the attached file to insert into the two tables.

The page loads without errors, but I get this message that the view is not updatable because the modification affects multiple base tables.

I thought this was the purpose of views?

Does anyone have any suggestions? I am using Dreamweaver MX and SQL Server.

Thanks!
NNo, that is not the purpose of views. Views are frequently not updateable, and I don't think it is ever possible to update different columns from different tables in the same view. Even a direct SQL Update statement will only update one table at a time, so you will need to issues separate update statements or handle the problem through triggers or cascading updates.

Truth is, views don't serve much purpose any more.

Good database application design principles dictate making all your updates through stored procedures. Your application should rarely if ever have direct access to the database tables, even for retrieving data.|||No, you can update the columns of each of the base table independantly (one or more UPDATE statements per base table), but you can't update multiple base tables in a single pass.

Thinking outside of the SQL box, a table represents a relational algebra entity. An entity has no inherant order for either columns or rows, they behave something like a hash in that respect.

Views represent a relational algebra result. A result can have order, there can be a first, middle, and last for both rows and columns in a view.

-PatP|||Views (with multiple base tables) can be updated at one shot by using INSTEAD OF trigger

Here is some supporting article from MSDN

Cheers

Benny
-----------------------

Modifying Data Through a View
You can modify data through a view in these ways:

Use INSTEAD OF triggers with logic to support INSERT, UPDATE and DELETE statements.

Use updatable partitioned views that modify one or more member tables.
If a view does not use an INSTEAD OF trigger or is not an updatable partitioned view, it can still be updatable provided that:

The view contains at least one table in the FROM clause of the view definition; the view cannot be based solely on an expression.

No aggregate functions (AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, VARP) or GROUP BY, UNION, DISTINCT, or TOP clauses are used in the select list. However, aggregate functions can be used within a subquery defined in the FROM clause provided that the derived values generated by the aggregate functions are not modified.

Note Partitioned views using the UNION ALL operator can be updatable.

No derived columns are used in the select list. Derived columns are result set columns formed by anything other than a simple column reference.
Guidelines for Modifying Data Through a View
Before you modify data through a view without using an INSTEAD OF trigger or an updatable partitioned view, consider these guidelines:

All data modification statements executed against the view must adhere to the criteria set within the SELECT statement defining the view if the WITH CHECK OPTION clause is used in the definition of the view. If the WITH CHECK OPTION clause is used, rows cannot be modified in a way that causes them to disappear from the view. Any modification that would cause this to happen is canceled and an error is displayed.

SQL Server must be able to resolve unambiguously the modification operation to specific rows in one of the base tables referenced by the view. You cannot use data modification statements on more than one underlying table in a single statement. Therefore, the columns listed in the UPDATE or INSERT statement must belong to a single base table within the view definition.

All the columns in the underlying table that are being updated and do not allow null values have values specified in either the INSERT statement or DEFAULT definitions. This ensures that all the columns in the underlying table that require values have them.

The data modified in the columns in the underlying table must adhere to the restrictions on those columns, such as nullability, constraints, DEFAULT definitions and so on. For example, if a row is deleted, all the underlying FOREIGN KEY constraints in related tables must still be satisfied for the delete to succeed.

A distributed partition view (remote view) cannot be updated using a keyset-driven cursor. This restriction can be resolved by declaring the cursor on the underlying tables and not on the view itself.
Additionally, to delete data in a view:

Only one table can be listed in the FROM clause of the view definition.|||Originally posted by blindman
Truth is, views don't serve much purpose any more.

what??!!

maybe not for use by the DBA, but for use by end users in a reporting environment, views are invaluable

"much purpose any more"?

what do you suppose the purpose of a view used to be then, before it got to where this purpose was diluted?

okay, here's an example

say a table is called Accounts and say it contains a column called LedgerCode and say the column values range from A to E, and now you have to change the table so that instead of values A to E, the LedgerCode becomes a numeric tinyint foreign key to a Ledger table with values A through Z

the mere fact that you can have a view with a join in it eliminates the need for the end user to figure out how to write a join

rename the table, change the table, declare a view called Accounts, build the join into the view, and voila, all existing code that used to select from the Accounts table still works

a long time ago i used to work in a shop where end users never got to use base tables, they were always given just views, and i can definitely see the logic behind that

it's called program-data independence|||Let me rephrase that...

Truth is, views don't serve much purpose any more, "IMHO".

I used to use views a lot too, specifically for program-data independence. Now, at least for application development, I always use Sprocs or UDFs.|||cool :cool:|||I believe you mean...

"Cool, IMHO." ;)|||indeed

burying application code inside sporcs and fuds is not cool to everybody, i admit -- especially those folks who would like to see a clear separation of application logic from proprietary database languages

usually i insist on declarative relational integrity but otherwise force application logic outside the database

you know, like so that your app is not dependent on any particular dbms

but sporcs and fuds are reasonably coolish, in my opinion, yeah|||Okey-dokey. I usually take the exact opposite approach, putting as much application logic into the RDBMS as possible, so that the application is not dependent on any particular interface. The reasoning is that these days people frequently want to access their data through different channels, such as a VB application, a Crystal Report, Access ADP project, Dot-Net, etc. By putting the application logic in the database you ensure consistent input and output and you avoid duplicating code. Let the the interface do what it does best: display the data and guide the user through it.

I guess the decision depends upon whether it is more likely that your application will need to be ported to a different RDBMS, or that users will come up with new requirements for accessing it. Perhaps I prefer the latter because the former results in boring "file cabinet" databases which frequently lack any sort of referential integrity. They just aren't as much fun or rewarding to work with as a database which is practically an application in itself.

Insert query firing Insert & Update trigger at the same time.

Hello All,
I have a table on which I have created a insert,Update and a Delete trigger. All these triggers write a entry to another audit table with the unique key for each table and the timestamp.

Insert and Update trigger work fine when i have only one of them defined.

However when I have all the 3 triggers in place and when i try to fire a insert query on the statement. It triggers both insert and update trigger at the same time and has the same timestamp in the audit table.

Insert trigger goes as
CREATE TRIGGER InsRecord ON [dbo].[tableA]
AFTER INSERT
AS
insert Audit(change_id,change_table,change_type,date_chan ge)
select uniqueid, srctable,'Insert',GetDate() from inserted

Update trigger goes as
CREATE TRIGGER UpdRecord ON [dbo].[tableA]
FOR UPDATE
AS
insert Audit(change_id,change_table,change_type,date_chan ge)
select uniqueid, srctable,'Update',GetDate() from inserted

Delete Trigger goes as
CREATE TRIGGER delRecord ON [dbo].[tableA]
FOR DELETE
AS
insert Audit(change_id,change_table,change_type,date_chan ge)
select uniqueid, srctable,'Delete',GetDate() from deleted

Note:This tableA has relations with 2 other tables on 1 field each from each table but i don't think it should matter.

Please advise how to prevent it.CREATE TRIGGER alteredRecord ON [dbo].[tableA]
FOR INSERT, UPDATE, DELETE
AS
BEGIN

...declare lngIns & lngDel

SELECT lngIns=count(col1)
from inserted

select lngDel=count(col1)
from deleted

IF lngIns>0 and lngDel=0
...inserted
else if lngIns>0 and lngDel>0
...updated
else if lngIns=0 and lngDel>0
...deleted
end

END

insert query fails (if form fields left empty)

Dear All,

I have created a table in my SQL server database, the problem i am facing is my insert query fails if i leave any form field empty (leave it blank). On my back-end table, only one field is mandatory, and others have been set with the constraint "allow null".

As per our business requirement, except one value is complusory while others are optional. If I enter all values in the form it works perfectly fine. Can you see in the code below - where am i possibly going wrong ?

<script language="VB" runat="server" >

Sub Page_Load(Src As Object, e As EventArgs)


If Page.IsPostBack Then

Dim ConLath As SqlConnection
Dim comLath As SqlCommand
Dim insertcmd

conLath = New SqlConnection("Data Source=SQLas;Initial Catalog=settle;User ID=sa;Password=password")
ConLath.Open()
insertcmd = "Insert into His_set values (@.t_d,@.s_p,@.p_s,@.v_oq,@.i_oq,@.v_qn,@.i_qn,@.v_qw,@.i_qw)"

comLath = New SqlCommand(insertcmd, ConLath)


comLath.Parameters.Add(New SqlParameter("@.t_d", SqlDbType.DateTime, 12))
comLath.Parameters("@.t_d").Value = trade_date.Text
comLath.Parameters.Add(New SqlParameter("@.s_p", SqlDbType.Decimal, 8))
comLath.Parameters("@.s_p").Value = sett_price.Text
comLath.Parameters.Add(New SqlParameter("@.p_s", SqlDbType.Decimal, 8))
comLath.Parameters("@.p_s").Value = post_close.Text
comLath.Parameters.Add(New SqlParameter("@.v_oq", SqlDbType.Int, 8))
comLath.Parameters("@.v_oq").Value = vol_oq.Text
comLath.Parameters.Add(New SqlParameter("@.i_oq", SqlDbType.Int, 8))
comLath.Parameters("@.i_oq").Value = oi_oq.Text
comLath.Parameters.Add(New SqlParameter("@.v_qn", SqlDbType.Int, 8))
comLath.Parameters("@.v_qn").Value = vol_qn.Text
comLath.Parameters.Add(New SqlParameter("@.v_qw", SqlDbType.Int, 8))
comLath.Parameters("@.v_qw").Value = vol_qw.Text
comLath.Parameters.Add(New SqlParameter("@.i_qn", SqlDbType.Int, 8))
comLath.Parameters("@.i_qn").Value = oi_qn.Text
comLath.Parameters.Add(New SqlParameter("@.i_qw", SqlDbType.Int, 8))
comLath.Parameters("@.i_qw").Value = oi_qw.Text


Try
comLath.ExecuteNonQuery()

Catch ex As SqlException
If ex.Number = 2627 Then
Message.InnerHtml = "ERROR: A record already exists with " _
& "the same primary key"
Else
Message.InnerHtml = "ERROR: Could not add record, please " _
& "ensure the fields are correctly filled out"
Message.Style("color") = "red"
End If
End Try

comLath.Dispose()
ConLath.Close()




End If
End Sub

</script>

I'm not surprised if it fails when you leave the mandatory field empty. But I assume that's not what you meant, right?

The problem here relates to casting. Your empty text box returns an empty string. This would be fine for a varchar column, but if you try this with a column of type int, it will fail. You need to explicitly insert a null value in this case.

You could try something like this:

comLath.Parameters("@.v_oq").Value = (vol_oq.Text =="" ? DBNull.Value : vol_oq.Text);
|||

thanks for your prompt reply.

apparently the conditional operator ? works if u are using C#.

I am using the language vb, this implies i will have to use the if and then conditonal block for each, right?

|||
VB has the tertial operator IIF which is similar to ? operator, although it behaves somewhat differently (VB evaluates all parameters). 
comLath.Parameters("@.v_oq").Value = IIF(vol_oq.Text =="", DBNull.Value, vol_oq.Text)

|||

thanks so much it worked :)

however, the issue now is when i try to display the columns with null values, it reports an error -

i have explicitly casted these values with their corresponding data types to defualt value other than null. But the problem is like for eg, in case of any integer type it i set it to default of "0", for our business purpose its misleading as they would be expecting the sell of items for that day to be "0".

this is my code:

Public Function CheckDBNull(ByVal obj As Object, _
Optional ByVal ObjectType As enumObjectType = enumObjectType.StrType) As Object
Dim objReturn As Object
objReturn = obj
If ObjectType = enumObjectType.StrType And IsDBNull(obj) Then
objReturn = ""
ElseIf ObjectType = enumObjectType.IntType And IsDBNull(obj) Then
objReturn = 0
ElseIf ObjectType = enumObjectType.DblType And IsDBNull(obj) Then
objReturn = 0.0
End If
Return objReturn
End Function

|||

Then what do you want to display if an integer column is null? If you want to leave that field blank, simply return an empty string...

|||hi thanks for all your help... i have resolved the above query... much appreciated

Sunday, February 19, 2012

Insert or Update Row if Primary key isn't pre-existing in table SQL 2000

I'm trying to extract data from our Accounting Database and use it in
another database that's used for our web site. Last month I created a SQL
Select Query to give me the product information I need to put into our web
site database. I then used DTS to copy that data from one database to
another. Now I need to update my web site database with any new products
that have been added into our Accounting database without changing any
existing rows in the web site database. Basically, I just need to be able
to add a new row for a product if the product ID (primary key) isn't
anywhere in my web site database. Here's my original query to retrieve
product info from the Accounting database:
SELECT DISTINCT IV00101.ITEMNMBR AS ID, IV00101.ITEMDESC AS Title,
IV00101.USCATVLS_2 AS Category
FROM IV00101 LEFT JOIN AARG_Inv_UserDef_Item ON IV00101.ITEMNMBR =
AARG_Inv_UserDef_Item.ITEMNMBR
WHERE ((IV00101.ITEMTYPE)=1 AND ((IV00101.USCATVLS_2)<>'box' And
(IV00101.USCATVLS_2)<>'replicator'
And (IV00101.USCATVLS_2)<>'components' And (IV00101.USCATVLS_2)<>'displays'
And (IV00101.USCATVLS_2)<>'Dist Audio'
And (IV00101.USCATVLS_2)<>'Dist Video' And (IV00101.USCATVLS_2)<>'Dist
Games' And (IV00101.USCATVLS_2)<>'Dist Softw'
And (IV00101.USCATVLS_2)<>'Dist Books' ))
ORDER BY IV00101.ITEMNMBR;
RESULTS
40139 James Earl Jones reads the Bible (CD/Small)
Devotional
40151 In Their Own Words: Space Race (CD/Small) Spoken
Word
40155 Old West Collection (CD/Small)
Spoken Word
40159 Lewis & Clark Collection (CD/Small)
Spoken Word
40162 Ingles (CD/Large)
Lang LearnColin wrote:
> I'm trying to extract data from our Accounting Database and use it in
> another database that's used for our web site. Last month I created
> a SQL Select Query to give me the product information I need to put
> into our web site database. I then used DTS to copy that data from
> one database to another. Now I need to update my web site database
> with any new products that have been added into our Accounting
> database without changing any existing rows in the web site database.
> Basically, I just need to be able to add a new row for a product if
> the product ID (primary key) isn't anywhere in my web site database.
> Here's my original query to retrieve product info from the Accounting
> database: SELECT DISTINCT IV00101.ITEMNMBR AS ID, IV00101.ITEMDESC AS
> Title,
> IV00101.USCATVLS_2 AS Category
> FROM IV00101 LEFT JOIN AARG_Inv_UserDef_Item ON IV00101.ITEMNMBR =
> AARG_Inv_UserDef_Item.ITEMNMBR
> WHERE ((IV00101.ITEMTYPE)=1 AND ((IV00101.USCATVLS_2)<>'box' And
> (IV00101.USCATVLS_2)<>'replicator'
> And (IV00101.USCATVLS_2)<>'components' And
> (IV00101.USCATVLS_2)<>'displays' And (IV00101.USCATVLS_2)<>'Dist
> Audio'
> And (IV00101.USCATVLS_2)<>'Dist Video' And (IV00101.USCATVLS_2)<>'Dist
> Games' And (IV00101.USCATVLS_2)<>'Dist Softw'
> And (IV00101.USCATVLS_2)<>'Dist Books' ))
> ORDER BY IV00101.ITEMNMBR;
> RESULTS
> 40139 James Earl Jones reads the Bible (CD/Small)
> Devotional
> 40151 In Their Own Words: Space Race (CD/Small)
> Spoken Word
> 40155 Old West Collection (CD/Small)
> Spoken Word
> 40159 Lewis & Clark Collection (CD/Small)
> Spoken Word
> 40162 Ingles (CD/Large)
> Lang Learn
Have a look at NOT EXISTS to insert only rows that do not exist. ORDER
BY clauses will just add unnecessary overhead unless you are inserting
in the destination table's clustered index order.
SELECT
COL1,
COL2
FROM
dbo.SOURCE_TABLE
WHERE
COL3 = 5
AND NOT EXISTS (
SELECT * FROM dbo.DESTINATION_TABLE WHERE DESTINATION_TABLE.COL4 =
SOURCE_TABLE.COL4)
David Gugick
Quest Software
www.imceda.com
www.quest.com|||Thank you! Both of your recommendations have helped me out. Here's my
final query
I ended up using the Not Exists query
AND NOT EXISTS (SELECT * FROM TopicsWeb.dbo.tblProduct WHERE
TopicsWeb.dbo.tblProduct.Product_ID = IV00101.ITEMNMBR);
Put the above into a Insert INTO statement and now I can synch the two DB's
"David Gugick" <david.gugick-nospam@.quest.com> wrote in message
news:uX4PPvC$FHA.2036@.TK2MSFTNGP14.phx.gbl...
> Colin wrote:
> Have a look at NOT EXISTS to insert only rows that do not exist. ORDER BY
> clauses will just add unnecessary overhead unless you are inserting in the
> destination table's clustered index order.
> SELECT
> COL1,
> COL2
> FROM
> dbo.SOURCE_TABLE
> WHERE
> COL3 = 5
> AND NOT EXISTS (
> SELECT * FROM dbo.DESTINATION_TABLE WHERE DESTINATION_TABLE.COL4 =
> SOURCE_TABLE.COL4)
>
> --
> David Gugick
> Quest Software
> www.imceda.com
> www.quest.com