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

Thursday, March 29, 2012

Configure data source insertion into SQL Server 2005 database - Express editions

I am attempting to insert information from Visual Web Developer 2005 using either the Gridview or Datalist controls into a SQL Server 2005 database and get stuck when defining the custom statement.

When I enter the text within the insert tab, the <next> button remains greyed out, preventing me from continuing to the next page.

If I copy the same text into the select tab, then I can continue with the wizard, however this raises other problems which may or may not be related (multiple insertions of the data into the SQL Server database table - possibly due to postback functions). I would rather use insert to confirm that my second problem is not because I am using the wrong option.

My question is:

Should I be able to use the insert function within VWD express or is this only available within the standard/pro editions?

Are you using SqlDataSource as the DataSource fo GridView/DataList? I tried that and I can edit customized INSERT command. Can you open QueryBuilder when you enter INSERT command?

|||

I am using SqlDataSource as the datasource as well as a valid connection string to my SQL Server Database.

I launched query builder to construct the sql command for insert. It brings up the appropriate table and columns and I have tried using both parameters and then free text responses with the same result.

If I copy the complete insert command (as constructed from query builder) and paste it into the select tab, then I am able to complete the wizard and my table is populated (albeit with multiple rows).

This implies that the sql statement is valid, however I would have thought that even a simple insert query - insert into table1 values("xxx") - would allow me to progress through the SqlDatasource wizard without any difficulty.

Sadly, I am unable to attach a screenshot which would make the visualisation of the problem that much easier.

To re-iterate my problem, I only get so far within the configure data source wizard - click a tab to create a SQL statement for that operation - <INSERT-TAB>, "sql_statement" before hitting a brick wall as both the next and finish buttons are greyed out.

I would appreciate any assistance you can provide on this matter.

Paul

Monday, March 19, 2012

Conditional SQL Insert Query

I have a simple ms access table with no primary key. I want to check if the value exists before it exists. I know there is way to do that directly using a insert clause without having a select statement but cannot seem to get it right.

Any help would be greatly appreciated.

Regards,

Vibhu Bansal.not sure if this is what you need but you can give it a try...

INSERT INTO <table> (field1, field2...) VALUES (value1, value2...)
WHERE (SELECT COUNT(*) FROM <table> WHERE <ColumnToCheck> = <ValueToCompare>) > 0;|||

I am looking for something similar but this gives an error in MsAccess saying semicolon expected. The semicolon is expected before "WHERE" clause!

Vibhu Bansal

|||can you post your code?|||

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO') where (select count(*) from tblTexas where ID='05320052')=0

The erro says "Semicolon expected" before where clause

Sorry guys was away on vacation so could post code earlier.

Any help would be beneficial.

Vibhu

|||

Hi there,

From experience, you cannot insert WHERE clause into an INSERT statement. Period.

I discovered this in the early days when I was just learning SQL and tried using an INSERT statement instead of an UPDATE statement and got an error kicked back at me.

I think there is an IF statement for SQL but am not sure - anyone else know?

Thanks,

medicineworker

|||

Vibhu Bansal wrote:

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO') where (select count(*) from tblTexas where ID='05320052')=0

The erro says "Semicolon expected" before where clause

Sorry guys was away on vacation so could post code earlier.

Any help would be beneficial.

Vibhu

Try this, use select instead of values()

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) select '05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO' where (select count(*) from tblTexas where ID='05320052')=0

|||

This does not work either...

select will require a table name or something...:)

|||Try doing a select command first i.e. select * from tblTexas where ID='05320052
then check @.@.ROWCOUNT for rows returned then the insert statement. Also Try selecting by table value rather than count. Like this:

select * from tblTexas where ID='05320052
if @.@.ROWCOUNT = 0
insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO')

Conditional SQL Insert Query

I have a simple ms access table with no primary key. I want to check if the value exists before it exists. I know there is way to do that directly using a insert clause without having a select statement but cannot seem to get it right.

Any help would be greatly appreciated.

Regards,

Vibhu Bansal.not sure if this is what you need but you can give it a try...

INSERT INTO <table> (field1, field2...) VALUES (value1, value2...)
WHERE (SELECT COUNT(*) FROM <table> WHERE <ColumnToCheck> = <ValueToCompare>) > 0;|||

I am looking for something similar but this gives an error in MsAccess saying semicolon expected. The semicolon is expected before "WHERE" clause!

Vibhu Bansal

|||can you post your code?|||

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO') where (select count(*) from tblTexas where ID='05320052')=0

The erro says "Semicolon expected" before where clause

Sorry guys was away on vacation so could post code earlier.

Any help would be beneficial.

Vibhu

|||

Hi there,

From experience, you cannot insert WHERE clause into an INSERT statement. Period.

I discovered this in the early days when I was just learning SQL and tried using an INSERT statement instead of an UPDATE statement and got an error kicked back at me.

I think there is an IF statement for SQL but am not sure - anyone else know?

Thanks,

medicineworker

|||

Vibhu Bansal wrote:

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO') where (select count(*) from tblTexas where ID='05320052')=0

The erro says "Semicolon expected" before where clause

Sorry guys was away on vacation so could post code earlier.

Any help would be beneficial.

Vibhu

Try this, use select instead of values()

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) select '05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO' where (select count(*) from tblTexas where ID='05320052')=0

|||

This does not work either...

select will require a table name or something...:)

|||Try doing a select command first i.e. select * from tblTexas where ID='05320052
then check @.@.ROWCOUNT for rows returned then the insert statement. Also Try selecting by table value rather than count. Like this:

select * from tblTexas where ID='05320052
if @.@.ROWCOUNT = 0
insert

into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair)

values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO')

Conditional SQL Insert Query

I have a simple ms access table with no primary key. I want to check if the value exists before it exists. I know there is way to do that directly using a insert clause without having a select statement but cannot seem to get it right.

Any help would be greatly appreciated.

Regards,

Vibhu Bansal.not sure if this is what you need but you can give it a try...

INSERT INTO <table> (field1, field2...) VALUES (value1, value2...)
WHERE (SELECT COUNT(*) FROM <table> WHERE <ColumnToCheck> = <ValueToCompare>) > 0;|||

I am looking for something similar but this gives an error in MsAccess saying semicolon expected. The semicolon is expected before "WHERE" clause!

Vibhu Bansal

|||can you post your code?|||

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO') where (select count(*) from tblTexas where ID='05320052')=0

The erro says "Semicolon expected" before where clause

Sorry guys was away on vacation so could post code earlier.

Any help would be beneficial.

Vibhu

|||

Hi there,

From experience, you cannot insert WHERE clause into an INSERT statement. Period.

I discovered this in the early days when I was just learning SQL and tried using an INSERT statement instead of an UPDATE statement and got an error kicked back at me.

I think there is an IF statement for SQL but am not sure - anyone else know?

Thanks,

medicineworker

|||

Vibhu Bansal wrote:

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO') where (select count(*) from tblTexas where ID='05320052')=0

The erro says "Semicolon expected" before where clause

Sorry guys was away on vacation so could post code earlier.

Any help would be beneficial.

Vibhu

Try this, use select instead of values()

insert into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair) select '05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO' where (select count(*) from tblTexas where ID='05320052')=0

|||

This does not work either...

select will require a table name or something...:)

|||Try doing a select command first i.e. select * from tblTexas where ID='05320052
then check @.@.ROWCOUNT for rows returned then the insert statement. Also Try selecting by table value rather than count. Like this:

select * from tblTexas where ID='05320052
if @.@.ROWCOUNT = 0
insert

into tblTexas(ID, DateBirth, Race, Gender, Height, Weight, Eyes, Hair)

values ('05320052', '11/08/1976', 'W', 'M', '509', '210', 'BRO', 'BRO')

Sunday, March 11, 2012

conditional split for insert or update cause dead lock on database level

Hi

I am using conditional split Checking to see if a record exists and if so update else insert. But this cause database dead lock any one has suggestion?

Thanks

Don't try and insert and update a table from the same data flow.

-Jamie

|||

My read from db is very expensive. We can't afford to read same data twice. So I use another merge join to force waiting on updating records to finish before I insert. This solve my problem. Thanks anyway.

aproaching Before:

conditional Split on newRecords and changedRecords, OLE DB Command was used to update changedRecords, OLE DB Destination was used to insert newRecords

aproaching Now:

Conditional Split on newRecords and changedRecords, OLE DB Command was used to update changedRecords,

Merge Join is used to left outer join newRecords with output of OLE DB Command ( this leave only newRecords is availible in output, but still wait for db update command finish), then

OLE DB Destination was used to insert output from merge join.

|||

Jun Fan wrote:

My read from db is very expensive. We can't afford to read same data twice. So I use another merge join to force waiting on updating records to finish before I insert. This solve my problem. Thanks anyway.

Why do you need to read data twice? Just push one of the data paths into a raw file and then insert/update/whatever that data from another dataflow.

-Jamie

|||

Thanks for sugestion. Pushing data into temp location (file or temp table) has been too slow for large amount new records. Another merge join to force wait on update finishing seems work great at this point.

Thanks again!

Jun Fan

|||

Jun Fan wrote:

Thanks for sugestion. Pushing data into temp location (file or temp table) has been too slow for large amount new records. Another merge join to force wait on update finishing seems work great at this point.

Thanks again!

Jun Fan

Have you tried raw files? They're lightning fast.

By the way, merge join does not ensure anything. It slows up one datapath, sure, but that in no way guarantees that you will prevent your locking problem.

-Jamie

|||

If performance is a concern, I'm suprised that using the OLEDB Command is OK, as it tends to be pretty slow. I have had much better success using a Conditional Split to direct new rows (Inserts) to an OLEDB Destination that writes directly to the target table, and directs the update rows to a permanent temp table. Then I use an Execute SQL Task to issue a batch Update statement after the data flow. During performance testing in the environments I work in, this has proven to be the fastest approach.

This is a pattern that many of the regular posters on this forum use very successfully.

conditional split for insert or update cause dead lock on database level

Hi

I am using conditional split Checking to see if a record exists and if so update else insert. But this cause database dead lock any one has suggestion?

Thanks

Don't try and insert and update a table from the same data flow.

-Jamie

|||

My read from db is very expensive. We can't afford to read same data twice. So I use another merge join to force waiting on updating records to finish before I insert. This solve my problem. Thanks anyway.

aproaching Before:

conditional Split on newRecords and changedRecords, OLE DB Command was used to update changedRecords, OLE DB Destination was used to insert newRecords

aproaching Now:

Conditional Split on newRecords and changedRecords, OLE DB Command was used to update changedRecords,

Merge Join is used to left outer join newRecords with output of OLE DB Command ( this leave only newRecords is availible in output, but still wait for db update command finish), then

OLE DB Destination was used to insert output from merge join.

|||

Jun Fan wrote:

My read from db is very expensive. We can't afford to read same data twice. So I use another merge join to force waiting on updating records to finish before I insert. This solve my problem. Thanks anyway.

Why do you need to read data twice? Just push one of the data paths into a raw file and then insert/update/whatever that data from another dataflow.

-Jamie

|||

Thanks for sugestion. Pushing data into temp location (file or temp table) has been too slow for large amount new records. Another merge join to force wait on update finishing seems work great at this point.

Thanks again!

Jun Fan

|||

Jun Fan wrote:

Thanks for sugestion. Pushing data into temp location (file or temp table) has been too slow for large amount new records. Another merge join to force wait on update finishing seems work great at this point.

Thanks again!

Jun Fan

Have you tried raw files? They're lightning fast.

By the way, merge join does not ensure anything. It slows up one datapath, sure, but that in no way guarantees that you will prevent your locking problem.

-Jamie

|||

If performance is a concern, I'm suprised that using the OLEDB Command is OK, as it tends to be pretty slow. I have had much better success using a Conditional Split to direct new rows (Inserts) to an OLEDB Destination that writes directly to the target table, and directs the update rows to a permanent temp table. Then I use an Execute SQL Task to issue a batch Update statement after the data flow. During performance testing in the environments I work in, this has proven to be the fastest approach.

This is a pattern that many of the regular posters on this forum use very successfully.

CONDITIONAL SPLIT and Bulk load Insert Error

i need to use a conditional split transformation to find missing column and direct the output of conditional split to my destination.

I have the following columns PatientId, Allergycode, SeverityCode

My requirement is to check whether value of a particular column is null or not null.

Please help.

Ronald

What part is a problem? Have you looked at transform documentation?
http://msdn2.microsoft.com/en-us/library/ms137886.aspx
To check for null values use IsNull method :)
http://msdn2.microsoft.com/en-us/library/ms141184.aspx|||

Hi Entin,

I have an access source table and the destination SQL table. in between i have the Conditional Split in which i use !ISNULL() the each column i have in my prescription table to test for missing columns and the Data conversion for changing the data type for the date column. Data conversion tranformation follows after the Split Condition Trans.

When i execute the package, it executes successfully but it doesnot write any rows to the destination table in SQL SERVER database.

Help out me bro.

Ronald

SSIS package "Conditional.dtsx" starting.

Information: 0x4004300A at Data Flow Task, DTS.Pipeline: Validation phase is beginning.

Information: 0x4004300A at Data Flow Task, DTS.Pipeline: Validation phase is beginning.

Information: 0x40043006 at Data Flow Task, DTS.Pipeline: Prepare for Execute phase is beginning.

Information: 0x40043007 at Data Flow Task, DTS.Pipeline: Pre-Execute phase is beginning.

Information: 0x4004300C at Data Flow Task, DTS.Pipeline: Execute phase is beginning.

Information: 0x40043008 at Data Flow Task, DTS.Pipeline: Post Execute phase is beginning.

Information: 0x40043009 at Data Flow Task, DTS.Pipeline: Cleanup phase is beginning.

Information: 0x4004300B at Data Flow Task, DTS.Pipeline: "component "SQL Server Destination" (322)" wrote 0 rows.

SSIS package "Conditional.dtsx" finished: Success.

|||How many outputs does your Conditional Split have? Which outputs are connected to Data Conversion transform and SQL Destination? Have you monitored the data flow during execution - do any row flow out of the output you are using?|||

My conditional Split has 14 outputs.

The conditional Split default output is connected to the data conversion.

Yes, I have monitored the data flow during execution. No, it does not.

|||So it probably means that each row satisfies at least one of the conditions, and no row falls back to the default output?|||

So, how do i go about this to make sure that, it writes rows to the destination table in SQL SERVER

Regards,

Ronald

|||

When i use case12 (MedicineCode) as an output to the Data conversion.

When i execute the package, it writes 57 rows to the destination table instead of 58 rows.

Ronald

SSIS package "Conditional.dtsx" starting.

Information: 0x4004300A at Data Flow Task, DTS.Pipeline: Validation phase is beginning.

Information: 0x4004300A at Data Flow Task, DTS.Pipeline: Validation phase is beginning.

Information: 0x40043006 at Data Flow Task, DTS.Pipeline: Prepare for Execute phase is beginning.

Information: 0x40043007 at Data Flow Task, DTS.Pipeline: Pre-Execute phase is beginning.

Information: 0x4004300C at Data Flow Task, DTS.Pipeline: Execute phase is beginning.

Error: 0xC0202009 at Data Flow Task, SQL Server Destination [322]: An OLE DB error has occurred. Error code: 0x80040E14.

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "The bulk load failed. Unexpected NULL value in data file row 27, column 3. The destination column (VisitType) is defined as NOT NULL.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "The bulk load failed. Unexpected NULL value in data file row 26, column 3. The destination column (VisitType) is defined as NOT NULL.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "The bulk load failed. Unexpected NULL value in data file row 25, column 3. The destination column (VisitType) is defined as NOT NULL.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "The bulk load failed. Unexpected NULL value in data file row 24, column 3. The destination column (VisitType) is defined as NOT NULL.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "The bulk load failed. Unexpected NULL value in data file row 23, column 3. The destination column (VisitType) is defined as NOT NULL.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "The bulk load failed. Unexpected NULL value in data file row 22, column 3. The destination column (VisitType) is defined as NOT NULL.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "The bulk load failed. Unexpected NULL value in data file row 21, column 3. The destination column (VisitType) is defined as NOT NULL.".

An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E14 Description: "The bulk load failed. Unexpected NULL value in data file row 20, column 3. The destination column (VisitType) is defined as NOT NULL.".

Information: 0x40043008 at Data Flow Task, DTS.Pipeline: Post Execute phase is beginning.

Information: 0x40043009 at Data Flow Task, DTS.Pipeline: Cleanup phase is beginning.

Information: 0x4004300B at Data Flow Task, DTS.Pipeline: "component "SQL Server Destination" (322)" wrote 57 rows.

Warning: 0x80019002 at Data Flow Task: The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.

Task failed: Data Flow Task

Warning: 0x80019002 at Conditional: The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.

SSIS package "Conditional.dtsx" finished: Failure.

|||

Ronaldlee Ejalu wrote:

So, how do i go about this to make sure that, it writes rows to the destination table in SQL SERVER

Each output of conditional split forms a separate data flow. If you want to insert this data, you need to either

1) have one SQL destination per output, or

2) connect the flows together with Union All transform, then have a single destination

Thursday, March 8, 2012

Conditional Insert in SQL Server 2000?

I need to do a conditional insert, and I am afraid that if I do it in 2 steps it will create bugs...
I have a table called customers and a table called locks
customers has 3 fields CustomerID, FirstName, and LastName
locks has fields LockID, CustomerID, UserID, SessionID, and TimeStamp
I need to check if there are any records in Locks for a CustomerID and if there are none, I need to insert One.
This is going to tell my application that this Customer record is locked so no one else can edit it, until the Lock record is deleted.
I just don't want to make 2 trips, One to check if the Lock exists, then One to insert the Lock, since this could allow 2 locks to be created if the timing is correct.
Any ideas or comments?This code from myPreventing Duplicate Record Insertion on Page Refresh article should do what you need (note the use of BEGIN TRANSACTION, EXISTS, and WITH (UPDLOCK

Listing 4 – Stored Procedure spAddEmployee_UsingExists

CREATEPROCEDURE spAddEmployee_UsingExists
(
@.FirstNamevarchar(50),
@.LastNamevarchar(50)
)
AS
DECLARE @.Resultint
BEGINTRANSACTION
IFEXISTS
(
SELECT
NULL
FROM
EmployeesWITH (UPDLOCK)
WHERE
FirstName = @.FirstNameAND
LastName = @.LastName
)
BEGIN
SELECT @.Result = -1
END
ELSE
BEGIN
INSERTINTO
Employees
(
FirstName,
LastName
)
VALUES
(
@.FirstName,
@.LastName
)
SELECT @.Result =@.@.ERROR
END
IF @.Result <> 0
BEGIN
ROLLBACK
END
ELSE
BEGIN
COMMIT
END
RETURN @.Result


Conditional Insert

I need to do a conditional insert. This is what I have tried, it does not work.
What am I doing incorrectly?

IF (SELECT COUNT(*) FROM TBL1 INNER JOIN
TBL2 ON TBL1.MODEL_ID = TBL2.MODEL_ID INNER JOIN
TBL3 ON TBL1.PRO_TYPE = TBL3.TYPE INNER JOIN
TBL4 ON TBL1.PRO_SITE = TBL4.WHDESC) > 0

INSERT INTO TBL5
SELECT TBL1.PRO_SITE, TBL1.MODEL_ID,
TBL1.NUM_SLOTS, TBL1.TARGET_DAYS, GETDATE() AS Expr1,
TBL3.TYPE_ID, NULL AS Expr2, TBL1.NUM_SLOTS AS Expr3, NULL AS Expr4, NULL
AS Expr5, 0 AS RAMP
FROM TBL1 INNER JOIN
TBL2 ON TBL1.MODEL_ID = TBL2.MODEL_ID INNER JOIN
TBL3 ON TBL1.PRO_TYPE = TBL3.TYPE INNER JOIN
TBL4 ON TBL1.PRO_SITE = TBL4.WHDESC

UPDATE TBL5
SET TEAMS=0
GO
UPDATE TBL5
SET TEAMS = (SELECT NUM_SLOTS
FROM TBL6 R1
WHERE (R1.TEAM_ID = TBL5.TEAM_ID)
)
WHERE (TEAM_ID =
(SELECT TEAM_ID
FROM TBL6 R3
WHERE (R3.TEAM_ID = TBL5.TEAM_ID)))
GO
UPDATE TBL5
SET TOTALTEAMS = TEAMS + RAMP
GO

I need to do a conditional because sometimes the select that returns data contains no records.

Thanks...Try this:

IF EXISTS
(SELECT 1
FROM TBL1
INNER JOIN TBL2 ON TBL1.MODEL_ID = TBL2.MODEL_ID
INNER JOIN TBL3 ON TBL1.PRO_TYPE = TBL3.TYPE
INNER JOIN TBL4 ON TBL1.PRO_SITE = TBL4.WHDESC)
BEGIN
UPDATE <stuff here>
END
ELSE
BEGIN
INSERT <stuff here>
END

Conditional insert

Hi All,
I think I am a little dense when it comes to understanding SSSI. I want to insert into a table (a) with data from a table (b) located on a different server where the data data from table (b) does not exist in table (a).
I know how to create the sql command but, exactly where does the command belong.
I don't see how or where the command should be.
Also, after the above insert I want to use the same data selected and insert into various other tables.
I have not been able to resolve this and any help is certainly appreciated.
Thanks,
RoyCheck this out:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=119489&SiteID=1

Saturday, February 25, 2012

Conditional For Insert Trigger

Sort of new to this, hoping for some help here.
I've got a table which you insert Scores and comments for Different
Issues. Each User may only input ONE score, but many comments per
issue.
I'm attempting to run a trigger which looks at the distinct users (in
the table) and then will either allow the comment AND score to be
Inserted if the User hasn't put in a score for that issue yet. OR if
the User already HAS input a Score, set the Score to NULL and allow the
rest of the record to be inserted.
My trigger works, but instead of letting the *New* User to put in the
score, it just nulls it.
Sorry if this is kind of long, but I hope I've explained it
sufficiently. I hope someone can help me out. Thanks in advance
This is my trigger :
CREATE TRIGGER trCheckUserResponses
ON dbo.tblIssues_Responses
FOR INSERT
AS
IF (SELECT UserID from Inserted) not in (select distinct UserID from
tblIssues_responses)
BEGIN
Update tblIssues_Responses
Set tblIssues_Responses.Score= Inserted.Score
From tblIssues_Responses AS A, Inserted AS B
Where A.Response_ID = B.Response_ID
END
ELSE
BEGIN
Update tblIssues_Responses
Set tblIssues_Responses.Score = NULL
From tblIssues_Responses AS A, Inserted AS B
Where A.Response_ID = B.Response_ID
ENDPlease post DDL and sample data.
ML
http://milambda.blogspot.com/

Friday, February 24, 2012

Conditional column NAME on insert/update

I need to dinamically select a column in which to insert based on a
parameter, I have this code, but it throws an incorrect syntax
error.
The value that I'm inserting is always static (the current date) what I
need to be dynamic is the column in which it'll be inserted.
How do I dinamically select a column to insert based on a parameter?
Create PROCEDURE dbo.UpdateDetalleOT (
@.eotId int, --Parameter
)
insert into OT (
select Case
when @.eotId = 1 THEN OTFechaBorrador
when @.eotId = 2 THEN OTFechaAAsignar
end
) values ......
Here's the explanation of the case:
Suppose that you have a Job Order that goes over diferrent states
(Draft, Confirmed, Assigned, Finished...)
Well, I need to save the Date when the Job Order changed it's state, so
I have the following columns in the JobOrder Table:
DraftDate : Date when the Job Order get's the Draft state
ConfirmedDate : Date when the Job Order get's the Confirmed state
AssignedDate : Date when the Job Order get's the Assignedstate
etc...
That's why I need to create a dynamic Insert/Update, because depending
the
state the Job Order will be saved...will depend which column
(DraftDate, ConfirmedDate, etc) to insert the current
date.
Best Regards
Fabio CavassiniYou should go out of your way to avoid dynamic SQL. If that means you have
to write several nearly identical insert statements, then so be it. A
little redundant code is a whole lot easier to understand and to maintain
and a whole lot more secure than dynamic SQL. You could also specify all
columns in the column list and then use CASE in a SELECT clause to insert
NULLs into the nonrelevant columns (That's what will be inserted anyway if
column values aren't supplied.).
"Fabio Cavassini" <cavassinif@.gmail.com> wrote in message
news:1137972528.339815.240160@.g14g2000cwa.googlegroups.com...
>I need to dinamically select a column in which to insert based on a
> parameter, I have this code, but it throws an incorrect syntax
> error.
> The value that I'm inserting is always static (the current date) what I
> need to be dynamic is the column in which it'll be inserted.
> How do I dinamically select a column to insert based on a parameter?
> Create PROCEDURE dbo.UpdateDetalleOT (
> @.eotId int, --Parameter
> )
> insert into OT (
> select Case
> when @.eotId = 1 THEN OTFechaBorrador
> when @.eotId = 2 THEN OTFechaAAsignar
> end
> ) values ......
> Here's the explanation of the case:
> Suppose that you have a Job Order that goes over diferrent states
> (Draft, Confirmed, Assigned, Finished...)
> Well, I need to save the Date when the Job Order changed it's state, so
> I have the following columns in the JobOrder Table:
> DraftDate : Date when the Job Order get's the Draft state
> ConfirmedDate : Date when the Job Order get's the Confirmed state
> AssignedDate : Date when the Job Order get's the Assignedstate
> etc...
> That's why I need to create a dynamic Insert/Update, because depending
> the
> state the Job Order will be saved...will depend which column
> (DraftDate, ConfirmedDate, etc) to insert the current
> date.
> Best Regards
> Fabio Cavassini
>|||"Fabio Cavassini" <cavassinif@.gmail.com> wrote in message
news:1137972528.339815.240160@.g14g2000cwa.googlegroups.com...
>I need to dinamically select a column in which to insert based on a
> parameter, I have this code, but it throws an incorrect syntax
> error.
> The value that I'm inserting is always static (the current date) what I
> need to be dynamic is the column in which it'll be inserted.
> How do I dinamically select a column to insert based on a parameter?
> Create PROCEDURE dbo.UpdateDetalleOT (
> @.eotId int, --Parameter
> )
> insert into OT (
> select Case
> when @.eotId = 1 THEN OTFechaBorrador
> when @.eotId = 2 THEN OTFechaAAsignar
> end
> ) values ......
> Here's the explanation of the case:
> Suppose that you have a Job Order that goes over diferrent states
> (Draft, Confirmed, Assigned, Finished...)
> Well, I need to save the Date when the Job Order changed it's state, so
> I have the following columns in the JobOrder Table:
> DraftDate : Date when the Job Order get's the Draft state
> ConfirmedDate : Date when the Job Order get's the Confirmed state
> AssignedDate : Date when the Job Order get's the Assignedstate
> etc...
> That's why I need to create a dynamic Insert/Update, because depending
> the
> state the Job Order will be saved...will depend which column
> (DraftDate, ConfirmedDate, etc) to insert the current
> date.
> Best Regards
> Fabio Cavassini
>
In an INSERT there is no need to do such a thing. Obviously ALL columns are
affected by an INSERT statement, so just specify values for the ones you
want to populate and defaults or nulls for the ones you don't.
In the case of UPDATE you can use the general form:
UPDATE tbl
SET col1 = COALESCE(@.col1, col1),
col2 = COALESCE(@.col2, col2),
col3 = COALESCE(@.col3, col3),
..
WHERE ...
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||I didn't have realized that every column is affected with the insert,
I'll use condition for the values...and use COALESCE for the update.
Thanks very much for your help
Best Regards
Fabio Cavassini|||This is how I implemented:

>INSERT INTO OT (OTFechaBorrador, OTFechaAAsignar, ThirdColumn, ...)
>SELECT CASE WHEN @.eotId = 1 THEN CURRENT_TIMESTAMP ELSE NULL END),
> CASE WHEN @.eotId = 2 THEN CURRENT_TIMESTAMP ELSE NULL END),
> CASE WHEN @.eotId = 3 THEN CURRENT_TIMESTAMP ELSE NULL END),
I include all columns and the insert, and then I conditionally select
the value (null or current date) according to the parameter value.
Best Regards
Fabio Cavassini

Conditional Column Name On Insert

I need to dynamic select a column in which insert a vale based on a
parameter value, I have this code, but it throws an incorrect syntax
error.

How do I dinamically select a column to insert based on a parameter?

Create PROCEDURE dbo.UpdateDetalleOT (
@.eotId int,
)

insert into OT (
select Case
when @.eotId = 1 THEN OTFechaBorrador
when @.eotId = 2 THEN OTFechaAAsignar
end
) values ...

Best Regards
Fabio Cavassini
http://www.pldsa.com--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1

Try something like this instead:

If @.eotID = 1
BEGIN
INSERT INTO OT (OTFechaBorrador)
VALUES ...
END

IF @.eotId = 2
BEGIN
INSERT INTO OT (OTFechaAAsignar)
VALUES ...
END
--
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)

--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv

iQA/AwUBQ9F9/oechKqOuFEgEQL0DwCfVQyA7xrkbFiBhXHJwcZwh6jlv1sAnj8 x
Ig0V5L9rm9Cpt13pG+Talbie
=0ECz
--END PGP SIGNATURE--

cavassinif@.gmail.com wrote:
> I need to dynamic select a column in which insert a vale based on a
> parameter value, I have this code, but it throws an incorrect syntax
> error.
> How do I dinamically select a column to insert based on a parameter?
> Create PROCEDURE dbo.UpdateDetalleOT (
> @.eotId int,
> )
> insert into OT (
> select Case
> when @.eotId = 1 THEN OTFechaBorrador
> when @.eotId = 2 THEN OTFechaAAsignar
> end
> ) values ...|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.|||On 20 Jan 2006 11:49:20 -0800, cavassinif@.gmail.com wrote:

>I need to dynamic select a column in which insert a vale based on a
>parameter value, I have this code, but it throws an incorrect syntax
>error.
>How do I dinamically select a column to insert based on a parameter?
>Create PROCEDURE dbo.UpdateDetalleOT (
>@.eotId int,
>)
>insert into OT (
> select Case
> when @.eotId = 1 THEN OTFechaBorrador
> when @.eotId = 2 THEN OTFechaAAsignar
> end
>) values ...
>
>Best Regards
>Fabio Cavassini
>http://www.pldsa.com

Hi Fabio,

You can't insert into just one column - you insert a complete row, and
you'll have to give values (either real values or NULL) for all columns.
Sure, the language permits you to leave out some columns, but that's
just a shorthand way for specifying that you want to insert the defined
DEFAULT value (if any) or NULL in all the other columns.

To do what you appear to want (and I *really* hope that this is an
extremely simplified illustration of the real problem, because if this
is your real procedure, you have much, much bigger problems), you can
either use the code posted by MGFoster, or use

INSERT INTO OT (OTFechaBorrador, OTFechaAAsignar)
SELECT CASE WHEN @.eotId = 1 THEN ... ELSE NULL END),
CASE WHEN @.eotId = 2 THEN ... ELSE NULL END)

--
Hugo Kornelis, SQL Server MVP|||Thanks for all your advices:

MGFoster:
Yes, this would be a solution...but the table in which I'm inserting
has more than 30 columns...the insert code is huge...and I wouldn't
like to copy the insert for just one column of difference.

--CELKO--
Here's the explanation of the case:

Suppose that you have a Job Order that goes over diferrent states
(Draft, Confirmed, Assigned, Finished...)
Well, I need to save the Date when the Job Order changed it's state, so
I have the following columns in the JobOrder Table:
DraftDate : Date when the Job Order get's the Draft state
ConfirmedDate : Date when the Job Order get's the Confirmed state
AssignedDate : Date when the Job Order get's the Assignedstate
etc...

That's why I need to create a dynamic Insert, because depending the
state the Job Order will be saved...will depend which column
(DraftDate, ConfirmedDate, etc) it will have to insert the current
date.

Hugo:
I don't want to select a dynamic value... the value will be always the
current date, I need to dinamically specify in which column I will
insert the current date

Best Regards
Fabio Cavassini|||On 22 Jan 2006 15:12:16 -0800, cavassinif@.gmail.com wrote:

(snip)
>Yes, this would be a solution...but the table in which I'm inserting
>has more than 30 columns...the insert code is huge...and I wouldn't
>like to copy the insert for just one column of difference.

Hi Fabio,

Hmmm. Maybe you could explain in some more detail what is the actual
business problem you're trying to solve. A parameter that governs in
which of 30 columns the current date has to be inserted sounds as if the
best solution would be a redesign of your table - but I can only say for
sure if I know more about your actual problem and your current table
structure.

(snip)
>Hugo:
>I don't want to select a dynamic value... the value will be always the
>current date, I need to dinamically specify in which column I will
>insert the current date

I had used ellipsis as a placeholder for the value to delete. Now that I
know it's the current date, I can complete my proposed code. I've also
added a third column and ellipsis to show how you can extend this to as
many columns as you need.

INSERT INTO OT (OTFechaBorrador, OTFechaAAsignar, ThirdColumn, ...)
SELECT CASE WHEN @.eotId = 1 THEN CURRENT_TIMESTAMP ELSE NULL END),
CASE WHEN @.eotId = 2 THEN CURRENT_TIMESTAMP ELSE NULL END),
CASE WHEN @.eotId = 3 THEN CURRENT_TIMESTAMP ELSE NULL END),
...

If called with @.eotId equal to 1, this will create a row with
CURRENT_TIMESTAMP in the first column (OTFechaBorrador) and NULL in the
two (or more) other columns. If @.eotId is 2, OTFechaAAsignar will be the
current datetime and the other columns are NULL. Etc, etc.

--
Hugo Kornelis, SQL Server MVP|||Do it in two steps: Insert the common column data first, then do an
update to the appropriate row/column based on the new entry and the
type.

Hugo Kornelis wrote:
> On 22 Jan 2006 15:12:16 -0800, cavassinif@.gmail.com wrote:
> (snip)
> >Yes, this would be a solution...but the table in which I'm inserting
> >has more than 30 columns...the insert code is huge...and I wouldn't
> >like to copy the insert for just one column of difference.
> Hi Fabio,
> Hmmm. Maybe you could explain in some more detail what is the actual
> business problem you're trying to solve. A parameter that governs in
> which of 30 columns the current date has to be inserted sounds as if the
> best solution would be a redesign of your table - but I can only say for
> sure if I know more about your actual problem and your current table
> structure.
> (snip)
> >Hugo:
> >I don't want to select a dynamic value... the value will be always the
> >current date, I need to dinamically specify in which column I will
> >insert the current date
> I had used ellipsis as a placeholder for the value to delete. Now that I
> know it's the current date, I can complete my proposed code. I've also
> added a third column and ellipsis to show how you can extend this to as
> many columns as you need.
> INSERT INTO OT (OTFechaBorrador, OTFechaAAsignar, ThirdColumn, ...)
> SELECT CASE WHEN @.eotId = 1 THEN CURRENT_TIMESTAMP ELSE NULL END),
> CASE WHEN @.eotId = 2 THEN CURRENT_TIMESTAMP ELSE NULL END),
> CASE WHEN @.eotId = 3 THEN CURRENT_TIMESTAMP ELSE NULL END),
> ...
> If called with @.eotId equal to 1, this will create a row with
> CURRENT_TIMESTAMP in the first column (OTFechaBorrador) and NULL in the
> two (or more) other columns. If @.eotId is 2, OTFechaAAsignar will be the
> current datetime and the other columns are NULL. Etc, etc.
> --
> Hugo Kornelis, SQL Server MVP|||The problem is your database design. Instead of 30 columns for dates
for all the events applicable to the job, you should have two tables:
The first table has the job identification, a date column, and a column
for the event or event identifier.
The second table is the lookup table of events. Most people would set
this up with a numeric identifier as the primary key, and a description
column for the event description.

HTH|||The problem is your database design. Instead of 30 columns for dates
for all the events applicable to the job, you should have two tables:
The first table has the job identification, a date column, and a column
for the event or event identifier.
The second table is the lookup table of events. Most people would set
this up with a numeric identifier as the primary key, and a description
column for the event description.

HTH|||Thanks for all the replies,

I implemented it as Hugo sayed, with condition in the value:

>INSERT INTO OT (OTFechaBorrador, OTFechaAAsignar, ThirdColumn, ...)
>SELECT CASE WHEN @.eotId = 1 THEN CURRENT_TIMESTAMP ELSE NULL END),
> CASE WHEN @.eotId = 2 THEN CURRENT_TIMESTAMP ELSE NULL END),
> CASE WHEN @.eotId = 3 THEN CURRENT_TIMESTAMP ELSE NULL END),

I haven't realized that in an insert...in fact all values are
modified...consequently I need to put the condition in the value.

>The problem is your database design. Instead of 30 columns for dates
>A parameter that governs in
>which of 30 columns the current date has to be inserted sounds as if the
>best solution would be a redesign of your table

I know..that there are many columns...but...the business model
requires it. In addition I don't like to have many tables in my
databases, it's too much simple to maintain a reduced (respecting
normal forms, of course) set of tables.

Best Regards
Fabio Cavassini

Conditional checks in SSIS.

I have two connections in a package pointing to two different databases
on the same server. I have to insert records from 'DB1' table 'Gender1'
to 'DB2' table 'Gender2'. Before I do that though, I have to make sure
the minimum value (of all the Gender Keys that are going to be
inserted) of 'DB1' 'GenderKey' (which is an identity field) is greater than the
maximum value of DB2-GenderKey (which is a primary key but not an
identity field). How can I do this simple check? I have to do this process for many different tables ....... Gender table is just an example. If someone can give an detailed explanation on which tasks to use and how to use them (as I am relatively new to SSIS) that'd be great.So you want to move the rows from DB1 that are newer than what you have in DB2.

You should use an Execute Task in the Control Flow to get the ISNULL(MAX(GenderKey) ,0) from DB2 and place that in a variable. Have another variable with EvaluateAsExpression=True that builds a SQL statement with your MaxGenderKey variable to get any rows where GenderKey in DB1 is greater than the MaxGenderKey from DB2. Set the data access mode of your OLE DB Source to "SQL command from variable" and specify this expression-based variable.
|||actually, i do not want to do insert at all. If the condition check is successfull, then do the insert otherwise abort the package? How do i do that?|||You could certainly do that. You'd get the MaxGenderKey from DB1 as well and compare them in a precedence constraint to prevent any further execution.

Unless you're changing your original purpose of inserting new records from DB1 to DB2, it seems simpler to just let it try. If there aren't any, then it won't find anything to do.
|||

Use one Execute SQL to get the Max value from DB2, and one to get the Max value from DB1. Store the values in variables, as Jay described. Then have a data flow to do the actual inserts. Have a precendence constraint between the 2 Execute SQL tasks, and one between the 2nd Execute SQL and the data flow. Right-click on the precedence constraint between the 2nd Execute SQL and the data flow task, and change the Evaluation Operation to Expression and Constraint. Leave the Value as Success, and change the Expression to compare the variables you created (something like MaxIDFromDB1 > MaxIDFromDB2). Execution will only flow to the data flow if the expression evaluates to TRUE.

Exec SQL > Exec SQL --(expression goes here)-> Data Flow

|||

I think I might be getting what you guys are trying to convey.

So here is what I did.

I added a Sequence Container.

1. I added a Execute Sql Task to it which brings the GenderKey from Prod and puts it in a Variable using the following query ..

SELECT [User::GenderKey_Prod] = ISNULL(MAX(GenderKey) ,0) FROM dbo.DIM_Gender

2. I added another Execute Sql Task which brings the GenderKey from Staging and puts it in another Variable using following query ..

SELECT [User::GenderKey_Stg] = MIN(dg.GenderKey) FROM medical.Fact_Claim mfc
INNER JOIN dbo.Dim_Patient dp ON
dp.PatientKey = mfc.PatientKey
INNER JOIN dbo.Dim_Gender dg ON
dp.GenderKey = dg.GenderKey
WHERE mfc.TaskID = ?

I added the connector from Prod to Stg (1 -> 2).

3. Then added another data flow task (which will actually transfer the data).

4. And added a connector from STG to this data (2 -> 3) flow task and on this connector I defined the expression check @.

[User::GenderKey_Prod] < @. [User::GenderKey_Stg] which if true, will execute the data flow task.

All this makes sense, however, I am having troubles on step 2. Where condition task a parameter called TaskId, this parameter is a

Package Level parameter I have added. I did the parameter mapping, but it keeps giving error on this step says 'Parameter Name is

Unrecognized'. Can you see anything wrong that I have done in Step 2 while defining runtime parameters?

|||

Ok, I think I found the issue. The Parameter name in mapping section has to be 0.

But I still have an issue, now the package is running and executing step 1 and 2, after than its just not executing step 3 even if the expression is true. How can i check the values of the variables I assigned value to in step 1 and 2 ?

|||

ASOOD wrote:

SELECT [User::GenderKey_Stg] = MIN(dg.GenderKey) FROM medical.Fact_Claim mfc
INNER JOIN dbo.Dim_Patient dp ON
dp.PatientKey = mfc.PatientKey
INNER JOIN dbo.Dim_Gender dg ON
dp.GenderKey = dg.GenderKey
WHERE mfc.TaskID = ?

On the Parameter Mapping page make sure you specify 0 for the Parameter Name to represent the first parameter.

I'm not too sure about your SELECT syntax. You know you have to set the ResultSet to Single Row and make an entry on the Result Set page? You'll specify the output column name (which in your query above is [User::GenderKey_Stg]) and select the variable.

You also need to cast the MIN and MAX to avoid and error from SSIS. Those will come back as an object datatype unless you do it like CAST(MIN(dg.GenderKey) AS int).
|||Right-click on step 3 and add a breakpoint to the OnPreexecute step. Then run (debug) the package. When processing stops, you can go to the Debug menu and show the locals window. From there, drill down until you find your variables. Hit the run button to continue.|||

JayH wrote:

You also need to cast the MIN and MAX to avoid and error from SSIS. Those will come back as an object datatype unless you do it like CAST(MIN(dg.GenderKey) AS int).

I have not had this problem... Can you post a repro?|||I was able to debug the values, the prod variables has a value of 0 (it should be 2), I ran the query in Enterprise Manager and it returns 2 so obviously the way i am assigning value in the variable is wrong. I tried casting it, it still always shows 0 ?|||

Phil Brammer wrote:

JayH wrote:

You also need to cast the MIN and MAX to avoid and error from SSIS. Those will come back as an object datatype unless you do it like CAST(MIN(dg.GenderKey) AS int).

I have not had this problem... Can you post a repro?

Sorry, I should have qualified the statement. It will only happen if your datatype in SQL is not int. I was testing with a table that had a smallint and thus had to supply a CAST.
|||

ASOOD wrote:

I was able to debug the values, the prod variables has a value of 0 (it should be 2), I ran the query in Enterprise Manager and it returns 2 so obviously the way i am assigning value in the variable is wrong. I tried casting it, it still always shows 0 ?

Did you set the ResultSet to "Single Row" and create a mapping between the result column and the variable?
|||You guys are the best!! Works like a charm now. Thank you all.|||Thanks for the example as I was trying to do the same thing for the first time.

Conditional checks in SSIS.

I have two connections in a package pointing to two different databases
on the same server. I have to insert records from 'DB1' table 'Gender1'
to 'DB2' table 'Gender2'. Before I do that though, I have to make sure
the minimum value (of all the Gender Keys that are going to be
inserted) of 'DB1' 'GenderKey' (which is an identity field) is greater than the
maximum value of DB2-GenderKey (which is a primary key but not an
identity field). How can I do this simple check? I have to do this process for many different tables ....... Gender table is just an example. If someone can give an detailed explanation on which tasks to use and how to use them (as I am relatively new to SSIS) that'd be great.So you want to move the rows from DB1 that are newer than what you have in DB2.

You should use an Execute Task in the Control Flow to get the ISNULL(MAX(GenderKey) ,0) from DB2 and place that in a variable. Have another variable with EvaluateAsExpression=True that builds a SQL statement with your MaxGenderKey variable to get any rows where GenderKey in DB1 is greater than the MaxGenderKey from DB2. Set the data access mode of your OLE DB Source to "SQL command from variable" and specify this expression-based variable.
|||actually, i do not want to do insert at all. If the condition check is successfull, then do the insert otherwise abort the package? How do i do that?|||You could certainly do that. You'd get the MaxGenderKey from DB1 as well and compare them in a precedence constraint to prevent any further execution.

Unless you're changing your original purpose of inserting new records from DB1 to DB2, it seems simpler to just let it try. If there aren't any, then it won't find anything to do.
|||

Use one Execute SQL to get the Max value from DB2, and one to get the Max value from DB1. Store the values in variables, as Jay described. Then have a data flow to do the actual inserts. Have a precendence constraint between the 2 Execute SQL tasks, and one between the 2nd Execute SQL and the data flow. Right-click on the precedence constraint between the 2nd Execute SQL and the data flow task, and change the Evaluation Operation to Expression and Constraint. Leave the Value as Success, and change the Expression to compare the variables you created (something like MaxIDFromDB1 > MaxIDFromDB2). Execution will only flow to the data flow if the expression evaluates to TRUE.

Exec SQL > Exec SQL --(expression goes here)-> Data Flow

|||

I think I might be getting what you guys are trying to convey.

So here is what I did.

I added a Sequence Container.

1. I added a Execute Sql Task to it which brings the GenderKey from Prod and puts it in a Variable using the following query ..

SELECT [User::GenderKey_Prod] = ISNULL(MAX(GenderKey) ,0) FROM dbo.DIM_Gender

2. I added another Execute Sql Task which brings the GenderKey from Staging and puts it in another Variable using following query ..

SELECT [User::GenderKey_Stg] = MIN(dg.GenderKey) FROM medical.Fact_Claim mfc
INNER JOIN dbo.Dim_Patient dp ON
dp.PatientKey = mfc.PatientKey
INNER JOIN dbo.Dim_Gender dg ON
dp.GenderKey = dg.GenderKey
WHERE mfc.TaskID = ?

I added the connector from Prod to Stg (1 -> 2).

3. Then added another data flow task (which will actually transfer the data).

4. And added a connector from STG to this data (2 -> 3) flow task and on this connector I defined the expression check @.

[User::GenderKey_Prod] < @. [User::GenderKey_Stg] which if true, will execute the data flow task.

All this makes sense, however, I am having troubles on step 2. Where condition task a parameter called TaskId, this parameter is a

Package Level parameter I have added. I did the parameter mapping, but it keeps giving error on this step says 'Parameter Name is

Unrecognized'. Can you see anything wrong that I have done in Step 2 while defining runtime parameters?

|||

Ok, I think I found the issue. The Parameter name in mapping section has to be 0.

But I still have an issue, now the package is running and executing step 1 and 2, after than its just not executing step 3 even if the expression is true. How can i check the values of the variables I assigned value to in step 1 and 2 ?

|||

ASOOD wrote:

SELECT [User::GenderKey_Stg] = MIN(dg.GenderKey) FROM medical.Fact_Claim mfc
INNER JOIN dbo.Dim_Patient dp ON
dp.PatientKey = mfc.PatientKey
INNER JOIN dbo.Dim_Gender dg ON
dp.GenderKey = dg.GenderKey
WHERE mfc.TaskID = ?

On the Parameter Mapping page make sure you specify 0 for the Parameter Name to represent the first parameter.

I'm not too sure about your SELECT syntax. You know you have to set the ResultSet to Single Row and make an entry on the Result Set page? You'll specify the output column name (which in your query above is [User::GenderKey_Stg]) and select the variable.

You also need to cast the MIN and MAX to avoid and error from SSIS. Those will come back as an object datatype unless you do it like CAST(MIN(dg.GenderKey) AS int).
|||Right-click on step 3 and add a breakpoint to the OnPreexecute step. Then run (debug) the package. When processing stops, you can go to the Debug menu and show the locals window. From there, drill down until you find your variables. Hit the run button to continue.|||

JayH wrote:

You also need to cast the MIN and MAX to avoid and error from SSIS. Those will come back as an object datatype unless you do it like CAST(MIN(dg.GenderKey) AS int).

I have not had this problem... Can you post a repro?|||I was able to debug the values, the prod variables has a value of 0 (it should be 2), I ran the query in Enterprise Manager and it returns 2 so obviously the way i am assigning value in the variable is wrong. I tried casting it, it still always shows 0 ?|||

Phil Brammer wrote:

JayH wrote:

You also need to cast the MIN and MAX to avoid and error from SSIS. Those will come back as an object datatype unless you do it like CAST(MIN(dg.GenderKey) AS int).

I have not had this problem... Can you post a repro?

Sorry, I should have qualified the statement. It will only happen if your datatype in SQL is not int. I was testing with a table that had a smallint and thus had to supply a CAST.
|||

ASOOD wrote:

I was able to debug the values, the prod variables has a value of 0 (it should be 2), I ran the query in Enterprise Manager and it returns 2 so obviously the way i am assigning value in the variable is wrong. I tried casting it, it still always shows 0 ?

Did you set the ResultSet to "Single Row" and create a mapping between the result column and the variable?
|||You guys are the best!! Works like a charm now. Thank you all.|||Thanks for the example as I was trying to do the same thing for the first time.

Conditional Bulk insert

Hi

I am doing bulk insert as follows. The @.lastUpdate, @.filePath, @.formatFile comes as a parametes to stored proc

INSERT INTO Categories

SELECT CategoryId, @.LastUpdate FROM OPENROWSET

(

BULK @.filePath ,

FORMATFILE = @.formatFile,

FIRSTROW =2

)

AS a

This works fine for me.

But my new requirement is that i shouldn't insert the CategoryId if it exists

How can we have conditional bulk insert? i am using Bulk insert as the file might have millions of category Ids.

Please provide your inputs that executes much faster

Best Regards,

~Mohan Babu

Try

INSERT INTO Categories

SELECT CategoryId, @.LastUpdate FROM OPENROWSET

(

BULK @.filePath ,

FORMATFILE = @.formatFile,

FIRSTROW =2

)

AS a

where a.CategoryID not in (select distinct CategoryId from Categories )

Conditional -- ?

What does "conditional" mean as a command? sp_who2 reports this for
some sessions, along with "insert" etc.

Thanks,
Jim Geissman(jim_geissman@.countrywide.com) writes:
> What does "conditional" mean as a command? sp_who2 reports this for
> some sessions, along with "insert" etc.

An IF or WHILE statement. Typically with a query in the condition, like
IF EXISTS(SELECT ...). If this query is long-running, or the longest
running in a stuck loop, CONDITIONAL is likely to turn up.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Thanks, Erland!

Erland Sommarskog wrote:
> (jim_geissman@.countrywide.com) writes:
> > What does "conditional" mean as a command? sp_who2 reports this for
> > some sessions, along with "insert" etc.
> An IF or WHILE statement. Typically with a query in the condition, like
> IF EXISTS(SELECT ...). If this query is long-running, or the longest
> running in a stuck loop, CONDITIONAL is likely to turn up.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Sunday, February 19, 2012

Concurrent updates

I have a table that I am auditing by having a trigger insert the Deleted row
to an audit table. .Net is calling the same stored procedure to update the
same row in the base table 4 times. The stored procedure subtracts a passed
in value from a column in the base table. After the code runs, the value in
the base table is correct, but the audit rows appear to show the the first
update subtracted first two amounts. The other weird thing is the time
stamp, which is generated from a getdate() is exactly the same for two of the
rows.
How tightly is the trigger code tied to the code that causes the trigger to
fire? We have tried playing with isolation levels on the .Net transaction
and this hasn't helped. Have a tripped on a bug, or am I doing something
wrong. Thanks for the help.
Todd
Can you post the trigger?
AMB
"pralnwuf" wrote:

> I have a table that I am auditing by having a trigger insert the Deleted row
> to an audit table. .Net is calling the same stored procedure to update the
> same row in the base table 4 times. The stored procedure subtracts a passed
> in value from a column in the base table. After the code runs, the value in
> the base table is correct, but the audit rows appear to show the the first
> update subtracted first two amounts. The other weird thing is the time
> stamp, which is generated from a getdate() is exactly the same for two of the
> rows.
> How tightly is the trigger code tied to the code that causes the trigger to
> fire? We have tried playing with isolation levels on the .Net transaction
> and this hasn't helped. Have a tripped on a bug, or am I doing something
> wrong. Thanks for the help.
> Todd
|||/*
* TRIGGER: [EFTAuditTrig]
*/
CREATE TRIGGER EFTAuditTrig ON EFT FOR UPDATE
as
Set NOCOUNT on
INSERT
EFTAudit([EFTID],[CreateDate],[SubmitDate],[SubmitedUserID],[TotalAmount],[CreateUserID],[UpdateUserID],[UpdateDate])
SELECT
[EFTID],[CreateDate],[SubmitDate],[SubmitedUserID],[TotalAmount],[CreateUserID],[UpdateUserID],[UpdateDate] FROM Deleted
"Alejandro Mesa" wrote:
[vbcol=seagreen]
> Can you post the trigger?
>
> AMB
> "pralnwuf" wrote:

Concurrent updates

I have a table that I am auditing by having a trigger insert the Deleted row
to an audit table. .Net is calling the same stored procedure to update the
same row in the base table 4 times. The stored procedure subtracts a passed
in value from a column in the base table. After the code runs, the value in
the base table is correct, but the audit rows appear to show the the first
update subtracted first two amounts. The other weird thing is the time
stamp, which is generated from a getdate() is exactly the same for two of th
e
rows.
How tightly is the trigger code tied to the code that causes the trigger to
fire? We have tried playing with isolation levels on the .Net transaction
and this hasn't helped. Have a tripped on a bug, or am I doing something
wrong. Thanks for the help.
ToddCan you post the trigger?
AMB
"pralnwuf" wrote:

> I have a table that I am auditing by having a trigger insert the Deleted r
ow
> to an audit table. .Net is calling the same stored procedure to update th
e
> same row in the base table 4 times. The stored procedure subtracts a pass
ed
> in value from a column in the base table. After the code runs, the value
in
> the base table is correct, but the audit rows appear to show the the first
> update subtracted first two amounts. The other weird thing is the time
> stamp, which is generated from a getdate() is exactly the same for two of
the
> rows.
> How tightly is the trigger code tied to the code that causes the trigger t
o
> fire? We have tried playing with isolation levels on the .Net transaction
> and this hasn't helped. Have a tripped on a bug, or am I doing something
> wrong. Thanks for the help.
> Todd|||/*
* TRIGGER: [EFTAuditTrig]
*/
CREATE TRIGGER EFTAuditTrig ON EFT FOR UPDATE
as
Set NOCOUNT on
INSERT
EFTAudit([EFTID],[CreateDate],[SubmitDate],[SubmitedUserID],
[TotalAmount],[CreateUserID],[UpdateUserID],[UpdateDate])
SELECT
[EFTID],[CreateDate],[SubmitDate],[SubmitedUserID],[Tota
lAmount],[CreateUserID],[UpdateUserID],[UpdateDate] FROM Deleted
"Alejandro Mesa" wrote:
[vbcol=seagreen]
> Can you post the trigger?
>
> AMB
> "pralnwuf" wrote:
>

Concurrent updates

I have a table that I am auditing by having a trigger insert the Deleted row
to an audit table. .Net is calling the same stored procedure to update the
same row in the base table 4 times. The stored procedure subtracts a passed
in value from a column in the base table. After the code runs, the value in
the base table is correct, but the audit rows appear to show the the first
update subtracted first two amounts. The other weird thing is the time
stamp, which is generated from a getdate() is exactly the same for two of the
rows.
How tightly is the trigger code tied to the code that causes the trigger to
fire? We have tried playing with isolation levels on the .Net transaction
and this hasn't helped. Have a tripped on a bug, or am I doing something
wrong. Thanks for the help.
ToddCan you post the trigger?
AMB
"pralnwuf" wrote:
> I have a table that I am auditing by having a trigger insert the Deleted row
> to an audit table. .Net is calling the same stored procedure to update the
> same row in the base table 4 times. The stored procedure subtracts a passed
> in value from a column in the base table. After the code runs, the value in
> the base table is correct, but the audit rows appear to show the the first
> update subtracted first two amounts. The other weird thing is the time
> stamp, which is generated from a getdate() is exactly the same for two of the
> rows.
> How tightly is the trigger code tied to the code that causes the trigger to
> fire? We have tried playing with isolation levels on the .Net transaction
> and this hasn't helped. Have a tripped on a bug, or am I doing something
> wrong. Thanks for the help.
> Todd|||/*
* TRIGGER: [EFTAuditTrig]
*/
CREATE TRIGGER EFTAuditTrig ON EFT FOR UPDATE
as
Set NOCOUNT on
INSERT
EFTAudit([EFTID],[CreateDate],[SubmitDate],[SubmitedUserID],[TotalAmount],[CreateUserID],[UpdateUserID],[UpdateDate])
SELECT
[EFTID],[CreateDate],[SubmitDate],[SubmitedUserID],[TotalAmount],[CreateUserID],[UpdateUserID],[UpdateDate] FROM Deleted
"Alejandro Mesa" wrote:
> Can you post the trigger?
>
> AMB
> "pralnwuf" wrote:
> > I have a table that I am auditing by having a trigger insert the Deleted row
> > to an audit table. .Net is calling the same stored procedure to update the
> > same row in the base table 4 times. The stored procedure subtracts a passed
> > in value from a column in the base table. After the code runs, the value in
> > the base table is correct, but the audit rows appear to show the the first
> > update subtracted first two amounts. The other weird thing is the time
> > stamp, which is generated from a getdate() is exactly the same for two of the
> > rows.
> >
> > How tightly is the trigger code tied to the code that causes the trigger to
> > fire? We have tried playing with isolation levels on the .Net transaction
> > and this hasn't helped. Have a tripped on a bug, or am I doing something
> > wrong. Thanks for the help.
> >
> > Todd