Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Firing A Trigger When A User Updates Data But Not When A Stored Procedure Updates Data


I have a project that consists of a SQL db with an Access front end as the user interface.  Here is the structure of the table on which this question is based:




Code Block

create table #IncomeAndExpenseData (
recordID nvarchar(5)NOT NULL,
itemID int NOT NULL,
itemvalue decimal(18, 2) NULL,
monthitemvalue decimal(18, 2) NULL
)
The itemvalue field is where the user enters his/her numbers via Access.  There is an IncomeAndExpenseCodes table as well which holds item information, including the itemID and entry unit of measure.  Some itemIDs have an entry unit of measure of $/mo, while others are entered in terms of $/yr, others in %/yr.

For itemvalues of itemIDs with entry units of measure that are not $/mo a stored procedure performs calculations which converts them into numbers that has a unit of measure of $/mo and updates IncomeAndExpenseData putting these numbers in the monthitemvalue field.  This stored procedure is written to only calculate values for monthitemvalue fields which are null in order to avoid recalculating every single row in the table.

If the user edits the itemvalue field there is a trigger on IncomeAndExpenseData which sets the monthitemvalue to null so the stored procedure recalculates the monthitemvalue for the changed rows.  However, it appears this trigger is also setting monthitemvalue to null after the stored procedure updates the IncomeAndExpenseData table with the recalculated monthitemvalues, thus wiping out the answers.

How do I write a trigger that sets the monthitemvalue to null only when the user edits the itemvalue field, not when the stored procedure puts the recalculated monthitemvalue into the IncomeAndExpenseData table?




View Complete Forum Thread with Replies

Related Forum Messages:
Changing A Field's Value When User Updates Data
Hello,
I am working on a project that involves one part where a field's value needs to be changed when the user updates the record.  Here is the situation in detail:
There is an InputData table where the user enters new records or changes existing records.  There is a field called "calculated" in this table which has a default value of 'no'.  A stored procedure runs math calculations on all the InputData records where the calculated field = 'no'.  At the end of this stored procedure, it sets the calculated field = 'yes'.  When new records are added by the user their "calculated" field value is 'no' by default so that the next time the stored procedure is executed, it only runs the math calculations on the new records.  The problem is, if a user changes an existing record, the "calculated" field needs to be changed from 'yes' to 'no' so that the stored procedure recalculates the math for the modified record.  How do I change the value from 'yes' to 'no' on records that the user modifies?
Thanks.

View Replies !
Error In Stored Procedure That Updates A Row
I have the following stored procedure:
CREATE PROCEDURE user1122500.sp_modifyOrganization(@Name nvarchar(100),@Location nvarchar(50),@Url nvarchar (250),@Org_Type nvarchar (50),@Par_Org_Id uniqueidentifier,@Row_Id uniqueidentifier,@Error_Code int OUTPUT,@Error_Text nvarchar(768) OUTPUT)ASDECLARE @errorMsg nvarchar(512)DECLARE @spName sysname
SELECT @spName = Object_Name(@@ProcID)SET @Error_Code = 0
IF @Url > ' '    BEGIN    UPDATE USER1122500.ORGANIZATION    SET URL = @Url ,UPDATED = GETDATE()    WHERE ROW_ID = @Row_Id        IF @@error <> 0        BEGIN        EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id,            N'URL', @Url        SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table        SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code)        RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg)        RETURN(@@error)        END    END
IF @Org_Type > ' '    BEGIN    UPDATE USER1122500.ORGANIZATION    SET ORG_TYPE = @Org_Type ,UPDATED = GETDATE()    WHERE ROW_ID = @Row_Id        IF @@error <> 0        BEGIN        EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id,            N'ORG_TYPE', @Org_Type        SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table        SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code)        RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg)        RETURN(@@error)        END    END
IF @Par_Org_Id IS NOT NULL    BEGIN    UPDATE USER1122500.ORGANIZATION    SET PAR_ORG_ID = @Par_Org_Id ,UPDATED = GETDATE()    WHERE ROW_ID = @Row_Id        IF @@error <> 0        BEGIN        EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id,            N'PAR_ORG_ID', @Par_Org_Id        SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table        SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code)        RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg)        RETURN(@@error)        END    END
IF @Name > ' ' OR @Location > ' '    BEGIN
    IF EXISTS (SELECT ROW_ID FROM USER1122500.ORGANIZATION WHERE NAME = @Name AND LOCATION = @Location)        BEGIN        EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'NAME', @Name,            N'LOCATION', @Location        SET @Error_Code = 55004 -- Error Message as created in the ERROR_LIST table        SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code)--        RAISERROR(@Error_Text, 10, 1, @spName, @Error_Code, 'ORGANIZATION', @errorMsg)        SELECT @Error_Text = (SELECT REPLACE(@Error_Text,'sp_name',@spName))        SELECT @Error_Text = (SELECT REPLACE(@Error_Text,'err_cd',@Error_Code))        SELECT @Error_Text = (SELECT REPLACE(@Error_Text,'tbl_name','ORGANIZATION'))        SELECT @Error_Text = (SELECT REPLACE(@Error_Text,'err_msg',@errorMsg))        RETURN(@Error_Code)        END
    IF @Name > ' '        BEGIN        UPDATE USER1122500.ORGANIZATION        SET NAME = @Name ,UPDATED = GETDATE()        WHERE ROW_ID = @Row_Id            IF @@error <> 0            BEGIN            EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id,                N'PAR_ORG_ID', @Name            SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table            SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code)            RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg)            RETURN(@@error)            END        END
    IF @Location > ' '        BEGIN        UPDATE USER1122500.ORGANIZATION        SET LOCATION = @Location ,UPDATED = GETDATE()        WHERE ROW_ID = @Row_Id            IF @@error <> 0            BEGIN            EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id,                N'LOCATION', @Location            SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table            SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code)            RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg)            RETURN(@@error)            END        END
    ENDGO
 
This is the code that runs it:
string strSP = "sp_modifyOrganization";
SqlParameter[] Params = new SqlParameter;
 
string strParOrgID = null;
if (this.ddlParentOrg.SelectedItem.Value != "")
{
strParOrgID = this.ddlParentOrg.SelectedItem.Value;
}
Params[0] = new SqlParameter("@Name", txtName.Text);
Params[1] = new SqlParameter("@Location", this.txtLocation.Text);
Params[2] = new SqlParameter("@Url", this.txtURL.Text);
Params[3] = new SqlParameter("@Org_Type", this.txtOrgType.Text);
//Params[4] = new SqlParameter("@Par_Org_Id", strParOrgID);
Params[4] = new SqlParameter("@Par_Org_Id", "CA1FBC83-D978-48F1-BCBC-E53AD5E8A321".ToUpper());

Params[5] = new SqlParameter("@Row_Id", "688f2d10-1550-44f8-a62c-17610d1e979a".ToUpper());
// Params[5] = new SqlParameter("@Row_Id", lblOrg_ID.Text);
Params = new SqlParameter("@Error_Code", -1);
Params[7] = new SqlParameter("@Error_Text", "");
Params[4].SqlDbType = SqlDbType.UniqueIdentifier;
Params[5].SqlDbType = SqlDbType.UniqueIdentifier;
Params.Direction = ParameterDirection.Output;
Params[7].Direction = ParameterDirection.Output;

try
{
this.dtsData = SqlHelper.ExecuteDataset(ConfigurationSettings.AppSettings["SIM_DSN"], CommandType.StoredProcedure, strSP, Params);
if (Params.Value.ToString() != "0")
{
lblError.Text = "There was an error: " + Params.Value.ToString()+ "###" + Params[7].Value.ToString();
lblError.Visible = true;
}
}
//catch (System.Data.SqlClient.SqlException ex)
catch (System.InvalidCastException inv)
{
lblError.Text = lblOrg_ID.Text + "<br><br>" + inv.ToString() + inv.Message + inv.StackTrace + inv.HelpLink;
lblError.Visible = true;
}
catch (Exception ex)
{
lblError.Text = lblOrg_ID.Text + "<br><br>" + ex.ToString();
lblError.Visible = true;
// return false;
}
This is the exception being generated:
System.InvalidCastException: Invalid cast from System.String to System.Guid.   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream)   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)   at System.Data.SqlClient.SqlCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)   at System.Data.Common.DbDataAdapter.FillFromCommand(Object data, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)   at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)   at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)   at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(SqlConnection connection, CommandType commandType, String commandText, SqlParameter[] commandParameters) in C:Program Files\_vsNETAddOnsMicrosoft Application Blocks for .NETData Access v2CodeVBMicrosoft.ApplicationBlocks.DataSQLHelper.vb:line 542   at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(String connectionString, CommandType commandType, String commandText, SqlParameter[] commandParameters) in C:Program Files\_vsNETAddOnsMicrosoft Application Blocks for .NETData Access v2CodeVBMicrosoft.ApplicationBlocks.DataSQLHelper.vb:line 458   at development.youthleadercert.com.share.ascx.organizationForm.btnAdd_Click(Object sender, EventArgs e) in c:documents and settingsmark rubinvswebcachedevelopment.youthleadercert.comshareascxorganizationform.ascx.cs:line 352
 
I have no idea what field is even causing the error, nor do I see that I'm even using a GUID field. I've been stuck on this for 2 days. Any help?
 

View Replies !
Problem With Stored Procedure Which Updates Rows
Hi dear users,
I have created procedure which main function is to update row of the table. Below, there is SQL code of this procedure.





Code Block

CREATE PROCEDURE Zakl_UpdateRow
    @zakl_id INT,
    @zakl_nazwa VARCHAR(25),
    @zakl_miasto VARCHAR(20),
    @zakl_ulica VARCHAR(30)
AS
UPDATE Zaklady SET
    Zakl_Nazwa=@zakl_nazwa,
    Zakl_Miasto=@zakl_miasto,
    Zakl_Ulica=@zakl_ulica
WHERE Zakl_ID=@zakl_id



When I execute this procedure I have to give all declared variables: "@zakl_id", "@zakl_nazwa" and so on. Sometimes I don't want to update all columns in the row but only one f.ex name of the street ("Zakl_Ulica"). And I want other colums of the row to stay the same ("Zakl_Nazwa","Zakl_Miasto"). There is no point in rewriting values of  "Zakl_Nazwa","Zakl_Miasto" as I want only to change value of "Zakl_Ulica".

this is execution clause





Code Block

EXECUTE Zakl_UpdateRow @zakl_id=70, @zakl_ulica='kosciuszki 7'
If I don't ascribe value to the variables (@zakl_nazwa, @zakl_miasto ), the columns in the row ("Zakl_Nazwa","Zakl_Miasto") should stay unchanged.

So what should I modify in my procedure, to have it working?


Best Regards

Maciej

View Replies !
Data Replication - Pushing Data Updates
Guys,

I have 14 databases, the last database - 14th one will have lookup tables only. The other 13 databases will have these lookup tables and data tables. At the end of each day I will make updates for lookup tables on 14th database, I want to be able to push the updates to any or some of the 13 databases. Look up tables will have only upto 100 rows, so I am not concerned about the bandwidth. What is the best way to accomplish this.

Any suggestions and inputs would help

Thanks

View Replies !
Trigger Firing Multiple Stored Procedure
DESCRIPTION: I have an FTP server set up to log via ODBC into a table FTPLog. The trigger on table FTPLog fires when new files are received to process and load the file via a stored procedure.

CREATE TRIGGER tr_new_file ON FTPLog
AFTER INSERT
AS
SET NOCOUNT ON
DECLARE @filename varchar(50), @logtime datetime
DECLARE c1 CURSOR
FOR SELECT filename, logtime
FROM inserted
OPEN c1
FETCH NEXT FROM c1
INTO @filename, @logtime
WHILE @@fetch_status = 0
BEGIN
EXEC sp1 @filename, @logtime
FETCH NEXT FROM c_inserted
INTO @filename, @logtime
END
CLOSE c1
DEALLOCATE c1
END

PROBLEM: There are multiple problems with this setup. The first problem is that when the stored procedure gets executed it takes a long time to process the file and the FTP server never returned a completion code to the ftp client and ended with a connection time out from the client. My users keep asking if the FTP failed but it didnt fail. The server returned a completion code too late.

PROBLEM2: When multiple files are ftp to the server on the same session, only the first one gets process. Even though my code loops through all the records because the processing takes a long time the second one never gets executed. If I replace the EXEC sp1 statement with a PRINT statement then it's working fine.

SOLUTIONS and SUGGESTIONS highly appreciated.

View Replies !
Stored Procedure Doesn't Recompile After Replication Updates Underlying Tables
We have on demand snapshot replication set up between 2 servers.  When the subscriber applies the snapshot, our stored procedures start executing very slowly.  Updating statistics and rebuilding indexes does not resolve the problem, however; executing sp_recompile on the affected stored procedures does fix the problem.  Is this a known issue with replication?  Is there a better workaround than manually recompiling stored procedures after every snapshot?

View Replies !
Troubleshooting Data Updates
I don't know if the title for the subject is appropriate here, anywayhere goes:This process was set up by someone and I have inherited it. I have asql2000 database that has about 13 tables that get populated with datafrom 3 different databases. I have identified where each of this datacomes from, and the stored procedures that do the updates, inserts, anddeletes, and the jobs that run these stored procedure to do theupdates, except for one table. The updates for all the other tablesare done through scheduled jobs. For the one table I know where thedata comes from and the stored procedure that needs to run to do theupdate on the table, however I have not been able to identify theprocess that runs the stored procedure.I am hoping that someone can give me a clue as to how to find out wherea stored procedure is being used - or any other hint as to how I couldgo about finding out how this table gets updated.ThanksKR

View Replies !
Transactional Replication - Propagating Updates As Updates
 

I am using SQL2005 transactional replication and need singleton updates to be propagate as updates and not as delete/insert  pairs as I am currently seeing.
 
In SQL 2000 - Trace flag T8207 can be used as described below

http://support.microsoft.com/kb/302341

The relevant extact from the article is as follows

"Organizations may find that sending updates to subscribers as DELETE and INSERT operations does not meet their business needs. For example, business rules might require update triggers to fire at the Subscriber. To accommodate these situations a new trace flag, 8207, is introduced in SQL Server 2000 Service Pack 1, which enables singleton updates for Transactional Replication. An update to a unique column that affects only one row (a singleton update) is replicated as an UPDATE and not as a DELETE or INSERT pair. If the update affects multiple rows, the update is still replicated as a DELETE or INSERT pair. "


How can I get the SQL 2000 behaviour on SQL 2005?  I have been advised that T8207 is not supported on SQL 2005.  I did try using T8207, but found that SQL then bugchecked whenever data was moved between partitions
 

Any suggestions would be much appreciated
 

aero1

 

View Replies !
Data Replication And Pushing Updates
Guys,

I have 14 databases, the last database - 14th one will have lookup tables only. The other 13 databases will have these lookup tables and data tables. At the end of each day I will make updates for lookup tables on 14th database, I want to be able to push the updates to any or some of the 13 databases. Look up tables will have only upto 100 rows, so I am not concerned about the bandwidth. What is the best way to accomplish this.

Any suggestions and inputs would help

Thanks

View Replies !
Make A Job That Updates Data By Row Amount
I need to make a job that will update up to 8000 rows with the list description of 'berkhold' to 'berknew' in SQL 2000. This is something that I have to do with several projects manually every day by doing the following 2 steps.

SELECT ListDescription, CRRecordID
FROM dbo_BerkleyGroupInventory
WHERE ListDescription ="BerkHold" AND CRCallDateTime<'1/1/2003' AND CRCallResultCode ='CC'
ORDER BY CRRecordID

I then scroll to the 8000th row and copy the CrrecordID and run the following query

UPDATE dbo.berkleygroupinventory
SET listdescription ='berknew'
WHERE ListDescription ='BerkHold' AND CRRecordID <=5968432 AND CRCallDateTime ='1/1/2003' AND CRCallResultCode='CC'

I'm sure there's an easier way to do this, but I'm very new to SQL and haven't figured it out yet

View Replies !
Updates Form Remote Data
I have been successful with DTS packages and various SQL statements. However, I have a new challenge. I have a table in an SQL Server database. One of the columns is employee number and a column for department number(which is not populated) In a remote AS400 file I have the employees number and department number. I want to create a package to connect to remote table and update SQL Server table with department number where the two tables match on the employee number.

View Replies !
Is It Possible To Manage Data Entry And Updates T
Hi Guys,

I'm using Visual Basic 2005 Express and SQL Server 2005 Express. I have textboxes on a VB form linked to 2 database tables.

I am wondering if it is possible to use just ONE BindingNavigator to manage data entry and updates to THE database tables. I initially thought I could manage the tables but have I encountered some problems:

i)When I entered a new record, and clicked on the SAVE BUTTON the new record the textboxes for the 1st table saves the record to the database, but the textboxes for 2nd table still retained data in them and are not saving theirs to the database.


ii) The same textboxes for the 2nd table are NOT allowing for updates too! Or, could it simply be that it is not possible to use this method for data entry and updates?


Thanks you.

View Replies !
Not Allowing Updates Row With Ntext Data Types
I am running a Access97 front end with a SQL Server 7 backend. On records with an ntext datatype, you are only allowed to update records if the ntext field is null. The tables are linked from access. You get a "cannot update linked table" and "ODBC error #306." Any suggestions??

View Replies !
What Is The Best Way To Manage Bulk Imports And Updates In Data?
I got anywhere from a couple hundred to a hundred thousand records that need to be updated or inserted into their SQL Server 2005 end destination.  What are some of the best ways to accomplish this?  Right now we are doing it manually through line by line updates and inserts.  Would I use BC or some other bulk import tool?

View Replies !
Downloaded 100 Data Changes (0 Inserts, 100 Updates, 0 Deletes, 0 Conflicts)
I recently rolled out replication on our production server (MS SQL 2000SP4) and every time a subscriber tries to sync the following alwaysappears in the Merge Agent History:"Downloaded 100 data changes (0 inserts, 100 updates, 0 deletes, 0conflicts)"Then at the very end of the "Action Messages" the following appears:"Merged 31489 data changes (453 inserts, 30893 updates, 143 deletes, 14resolved conflicts)."Each sync always produces this large result. I don't understand what ishappening and why such a large amount of changes are suppose to behappening. I could sync directly after the previous and get the sameresult.There are only 4 subscribers that merge with the publisher and all getthe same types of changes appearing.Also MSmerge_contents table doesn't seem to be cleaned up after allhave synced, the table always contains approx 30000+ records.Can anyone help please??

View Replies !
Merge Data From Two Tables Into One Table - No Updates/only Insert
 
Hi all,,
 
I posted the questions in sql forum and got good sql statement to work with it.. However, I want to see if there is a way to do it in SSIS..
 
May be this is really basic questions but I am having hard time to do it in sql server 2005 SSIS..
 
I have a flat file that I want to merge with table in SQL server 2005.
 
1> I have successfully created a data flow task to import data from flat file to Table X (new table I created for this package).
 
Now here is my question.
I have a Table A already in the database with the same column structure as of TableX (Both the tables have 20 columns/same Name/Same design).
 
I want to merge Table A and Table X and stored the data in TableA. However, I just don't want to merge blindly, I need to insert a new row in Table A only if the same row does not exist in Table A (there is no primary key, i am looking certain fields to see if the rows are same).. 
 
Here is an example:
Table A
--------------
1 test test1 test2 test3 test4 test5
2 test test6 test7 test8 test9 test10
 
Table X
------------
1 test test1 test2 test99 test4 test5
2 test test98 test97 test 96 test95 test94
--------------------------------------------------------
Now, I want to only insert row 2 of Table X since there is match on 4 of the fields in row1.. 
The new Table A should look like
 
NEW Table A'
-----------------
    
test test1 test2 test3 test4 test5
test test6 test7 test8 test9 test10
test test98 test97 test 96 test95 test94

 
------------------------------------
I think, I could do this using Execute SQL task and write all the code in sql, but that will be cumbersome and time consuming.. Is there a simpler way to achieve this?
 
Thanks in advance.
 

View Replies !
Question About Automating Data Conversion And Updates To A Table In SQL Database
Hello,
 
I will be getting data in either Excel or Access form on a daily basis. I would like to automate the process of converting this (excel or access) data to a table in an existing SQL  database.  Since this conversion needs to performed on a daily basis, note that I need to update the table that contains data from the day before.
 
Is it possible to do this and if it is possible, can someone tell me how to do it.
 
Thanks in advance,
 
Joe green

View Replies !
Create A Data Flow In SSIS Wich Updates Som Rows.
Hi,

I have a table customer wich has the columns phone_number(char type) and ok_to_call(bit type). There are already data in the table and the column ok_to_call only contains the value false for every row.

Now i want to update the latter column. I have a text file with a list of phone numbers and i want that all the rows in the Customer table(phone_number column)that matches the number in the text file to update ok_to_call to true.

This is to be done in SSIS(Integration Services). I'm new at this and i've looked around that tool but is a lot of items, packages and stuff so i dont know where to begin.

Would appreciate help on how to solve this issue in SSIS. What controlflow/Data flows to use,wich items and packages to use, how to configure and how to link together?

Regards
/Tomas

View Replies !
Help Setting Up Trigger That Updates/add
Hi!

I have a history table with this setup:
[MID
PK [IIN
[NUM_EVENTS
ACTION

NUM_EVENTS starts from 1 and adds up depending on the number of logs that MID-IIN combination has.

I have a Latest table as well that has the same layout as the History table.

What I need is to create a trigger in the History table that will:

1. Add a record in the Latest if that MID-IIN combination does not exist in the Latest.

OR

2. Update the record with latest NUM_EVENT for that specific record if it already exists.

Example:

History:
MID - 03
IIN - 00001
NUM_EVENTS - 1

Trigger should add this to the Latest table if it does not exist.

If someone adds another entry for this MID-IIN combination like:
MID - 03
IIN - 00001
NUM_EVENTS - 2

The trigger should update the previous record in Latest to reflect this newly inserted record.

Thanks in advance.

View Replies !
Trigger And Any Number Of Updates
I've a system of users and let's call em subusers. Every User becomes an automatic generated login when entered into the database. Every subuser has a reference to his user and no login, cause only thr root in the chain is able to login. But when the user gets deleted, all subusers become a new user. I've done this with a trigger changing the superUser Value=0:

create trigger abc on Users AFTER DELETE
as
declare @h int
SELECT @h = id FOM inserted
UPDATE Users SET superUser=0 WHERE superUser=@h

Furthermore the trigger deletes all additionally data of the user.
Since every subuser of the deleted user becomes a user himself for every subuser a new Login must be created. I'm using an update triger for this task:

1: create trigger userUpdate on Users After Update
2: AS
3: DECLARE @superold int
4: @supernew int
5: @name nvarchar(55)
6: @date smalldatetime
7: if UPDATE(superUser)
8: begin
9: SELECT @superold= superUser FROM deleted
10: SELECT @supernew=superUser FROM inserted
11:
12: if @superold <> @supernew
13: begin
14: if @superold = 0
15: begin
16: DELETE FROM UserLogin WHERE id=@superold
17: end
18: else if @supernew=0
19: begin
20: SELECT @name=Name,@date=Date from inserted
21: execute createLogin @supernew,@name,@date
21: end
22: end
23: end

The problem is in line 20 and 21, cause the values @name and @date containing only the last updated user(the last entry in the inserted table) thus only for the last user a new Login is created whereas the others become the state user but no login was created. What i need is a method to loop over all entrys in the tables inserted btw. deleted.
Does anybody know how to achieve this, looping the tables and executing a stored procedure for every entry?

bye

View Replies !
Instead Of Trigger And In-Place Updates
 

Converting an existing application, I have a table:
 

create table problem
(

building   char(3),
function   char(4),
sqft         int,
pct         dec(5,2)
)
 
[pct] is a problem because it depends on it's own row and the sum of all other rows for the same building:

pct = sqft / sum(sqft) over building
 
I want to create a trigger to update the pct column in the database instead of any business layer.  But, because it's updating itself I will use an Instead Of trigger that is separate from the table's Insert & Delete triggers.
 
The table has a primary key defined such that 'In-Place' updates will be used, that was a technique for reducing disk activity way back when and I can find no reference to it in SQL2005 BOL.
 
My question is, does the 'Inserted' table still exist for 'In-Place' updates?  Or more basically, does the In-Place update still exist?
 
Thanks.

View Replies !
Does The Configure Data Source Wizard Work For Updates,Inserts, And Deletes ?
Ok, I think this may have a simple answer. Basically I have no problems in setting up QueryString/Control/etc parameters when I use SELECT in the Configure Data Source Wizard as it prompts me for the necessary parameters. But when I try to use the Configure Data Source Wizard with an UPDATE, INSERT or DELETE it does NOT prompt me for the required parameters.Is this a bug or am I just missing something? Do I have to put them in manually or something?Thanks! 

View Replies !
Trigger Which Updates The Other Table Rows
I have a table called SomeTable. In This table there is a column called SomeDefaultValue of type bit. I dont want more than two rows to have SomeDefaultValue = true. So, i want when i update or insert with SomeDefaultValue set to true, the Trigger must reset all the other rows's SomeDefaultValue column to False. Any help???

View Replies !
Trigger To Handle Multirow Updates
I am trying to implement trigger which can handle multirow updates and which is running on replicated table. So I want it never fails as trigger failure brakes replication. 

So:

CREATE TRIGGER on_person_update

BEGIN

-- create temp table

-- populate temp table with Inserted values (I do not need Deleted as PK never change)

COMMIT TRAN

-- Am I right that this insures updates on replicated table will never be rollback after this commit?

BEGIN TRAN A

-- Make a checkpoint here to be able to rollback at any time to this point if something wrong inside loop.

SAVE TRAN MyTran

-- Start looping in temp table

-- RUN DML statement to make neccesary changes for each record in temp table

-- Does it make any sense to do this (IF @ERR below)? When I am trying in DML insert string value into integer column it never gets to IF statement - terminates straight away.

-- Reason why I think I need it as this trigger might be called by another trigger and top level trigger will get an error and can make a decision based on this.

 IF @ERR <> 0
 BEGIN
  ROLLBACK TRAN MyTran
  RAISERROR('Insert or Update failed in on_person_sls_update trigger with error: %s', 16, 1, @ERR)
  RETURN  
 END

-- End looping temp

-- Do I need here COMMIT TRAN A or trigger will make commit anyway?

END

Why all of this?

Data changed on distributor and arrive to subscriber as a transaction.

We have a trigger on replicated table which will update replicated table in any way but after that it will update another database on subscriber.

This trigger should be able to handle multirow updates.

When this trigger updates another database it runs DML which fires other triggers so they become nested, if I am right. Our trigger should always accept changes from distributor as if it fails replication brakes but after data saved in temp table none  or all changes have to be made.

May be I am copmpletely wrong with this template - hope somebody will help.

Thank you,

 

Igor 

 

 

View Replies !
User Updates
Hi all,

I recently inherited multiple databases for a research study. These databases use an Access front end with the tables stored on SQL Server. Currently, there is a folder for each database on a network drive. I make changes to the front ends (forms, reports etc.) in a development version of the dbs, test them, have a user test them, and then import them to the production front end.

Each user has a copy of the front end on their 'C:' drive. The previous developer put together a separate VB app that copies the changed mdb files from the network drive to their 'C:' drive. This doesn't seem like the best solution to me but I haven't come up with a better one. I would appreciate any input.

Thanks,

Monk

View Replies !
Problem: Trigger And Multiple Updates To The Table
Hey, I have couple of triggers to one of the tables. It is failing if I update multiple records at the same time from the stored procedure.

UPDATE
table1
SET
col1 = 0
WHERE col2 between 10 and 20

Error I am getting is :

Server: Msg 512, Level 16, State 1, Procedure t_thickupdate, Line 12
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

What is the best possible way to make it work? Thank you.

View Replies !
How To Catch Multiple Updates Done To A Table With A Trigger?
I was able to catch one update but not multiple updates or batch updates done to the table. I know the updated records are residing in inserted and deleted tables. Without using cursors, how can i read and compare all the rows in these two tables?
 
 
Following is the table structure:
 
Customer_Master(custmastercode, customer_company_name,updated_by)
 
Following is the trigger:
 

ALTER TRIGGER [TR_UPDATE_CUST]

ON [dbo].[CUSTOMER_MASTER]

AFTER UPDATE

AS

BEGIN



SET NOCOUNT ON;



 
IF EXISTS (SELECT * FROM inserted)

BEGIN

 
declare @custcode int

Declare @message varchar(5000)

Declare @custommessage varchar(2000)
Declare @CUSTMASTERCODE int 

Declare @CUSTOMER_COMPANY_NAME varchar(50)
 
Set @message = 'Changes in customer account number ' + Cast ((@custcode) as varchar(10)) + ': '

 

select @custcode = [CUSTMASTERCODE],@UPDATED_BY = [UPDATED_BY] from inserted

 
Set @message = 'Changes in customer account number ' + Cast ((@custcode) as varchar(10)) + ': '

 
IF(update([CUSTOMER_COMPANY_NAME]))

Begin

select @UCUSTOMER_COMPANY_NAME = [CUSTOMER_COMPANY_NAME] from deleted

select @CUSTOMER_COMPANY_NAME = [CUSTOMER_COMPANY_NAME] from inserted

Set @custommessage = 'Customer company name changed from ' + @UCUSTOMER_COMPANY_NAME + ' to ' + @CUSTOMER_COMPANY_NAME + '.'

Set @message = @message + @custommessage

End
 

Set @message = @message + ' Updated by ' + @UPDATED_BY + ' at ' + CAST(getdate() AS VARCHAR(20))+ '.'

 
INSERT INTO [CHANGE_HISTORY]

([CUSTMASTERCODE]

,[CHANGE_DETAILS])

VALUES (@custcode, @message)

END

END

View Replies !
Logging Batch Updates Without Using A Trigger Or A Cursor
Hi,
 
Does anyone know if there's a way to log batch updates done using SQL queries without using a trigger or a cursor?
 
Thanks in advance,
Vinod

View Replies !
Selective Updates Based On User
We have a Table that contains a schedule. The schedule has certain pieces of information that are required to be updated by certain members of the
organization, specifically Shift, Start Date, and Line. Each record also has a column for the customer that it is for.

The schedule has a Column, [CSR] which lists the name of the person who is responsible for updating it. Format of that is domainnamejohndoe

What we would like to do is block domainnamejohndoe from being able to update or insert on any of the records that he is not responsible for.

So if he attempts to change the shift for example, it denies the change and possible pops up an error indicating that the change was blocked because he is not the responsible party.

Input in this is through a query which views the table data in MS Access. It cannot be moved to a Form without some serious redesign, so I cannot put the block in there. I assumed that this could be blocked with a Trigger that checks the [CSR] column, matches it to the logged in user through the suser_sname(suser_sid()) and then either allows or denies the update.

So is this a viable idea, or should I explore the move to an input form and make the change there in MS Access via VBA.

At first we started with just an audit trail, but I started to think that the audit trail would be needed only for records that should be allowed to be changed and that we should deny changes to those who are not allowed to make them.

Below is the audit trail trigger, I figure that the change should occur somewhere within that first IF statement, or make the first IF the second, and the first should be the permission check.

At this point I am stuck as to how to block the updates. I tried using Deny but that was not working. Filtering the results by only showing the logged in user their records is not an option as they need visibility to the entire schedule.

This is for SQL 2000 SP4/Windows 2000 SP4


CREATE TRIGGER audit_mschange
ON dbo.T_PP_Table_2
FOR update AS
IF (UPDATE([Start Dt]) OR Update(shift) or Update
(comments)
or Update(status) or Update (line))
BEGIN

INSERT INTO T_MS_RB_AUDIT

(ord_no,line_tank_old,line_tank_new,shift_old,shif t_new,comments_old,comments_new,status_old,status_ new,trx_dt,trx_username,
start_dt_old,start_dt_new)

SELECT ins.[PP Ord No],
del.line,ins.line,
del.shift,ins.shift,
del.comments,ins.comments,
del.status, ins.status,
getdate(),
suser_sname(suser_sid()),
del.[Start Dt],
ins.[Start Dt]
FROM inserted ins, deleted del
WHERE ins.[PP Ord No]=del.[PP Ord No] AND
ins.autonumber=del.autonumber AND
(ins.status <> del.status OR ins.[Start Dt] <>
del.[Start Dt] or ins.status <> del.status
or ins.comments <> del.comments or ins.line <>
del.line )
END

View Replies !
Tracking User Updates On Records In SQL 7.0
Does anyone know of a good strategy for tracking which user was the last to update a record. I have attempted putting a trigger on the table so that when certain fields are updated the field called 'userid' will be set something like the following

UPDATE userid
SET userid = user

Obviously this changes the 'userid' field for every record to the value of the current user. I guess I am having some trouble with the WHERE clause of this statement. I just want the current record, the one whose updates are firing the trigger, to be modified. Is there a better way to do this? I guess to position the update I have to set a cursor on this record but I have so far had no luck. ANy tips?

Anthony

View Replies !
Importing Data In Datatable Using SSIS Package Trigger On Insert Is Not Firing On That Table
Hi
I am Importing data in datatable using SSIS package . I made trigger on that table on insert. The trigger on insert is not firing on that table
Please help
Thanks
CP

View Replies !
How Can I Do A Multiple Insert Or Multiple Updates Or Inserts And Updates To The Same Table..
Hi...
 I have data that i am getting through a dbf file. and i am dumping that data to a sql server... and then taking the data from the sql server after scrubing it i put it into the production database.. right my stored procedure handles a single plan only... but now there may be two or more plans together in the same sql server database which i need to scrub and then update that particular plan already exists or inserts if they dont...
 
this is my sproc...
 ALTER PROCEDURE [dbo].[usp_Import_Plan]
@ClientId int,
@UserId int = NULL,
@HistoryId int,
@ShowStatus bit = 0-- Indicates whether status messages should be returned during the import.

AS

SET NOCOUNT ON

DECLARE
@Count int,
@Sproc varchar(50),
@Status varchar(200),
@TotalCount int

SET @Sproc = OBJECT_NAME(@@ProcId)

SET @Status = 'Updating plan information in Plan table.'
UPDATE
Statements..Plan
SET
PlanName = PlanName1,
Description = PlanName2
FROM
Statements..Plan cp
JOIN (
SELECT DISTINCT
PlanId,
PlanName1,
PlanName2
FROM
Census
) c
ON cp.CPlanId = c.PlanId
WHERE
cp.ClientId = @ClientId
AND
(
IsNull(cp.PlanName,'') <> IsNull(c.PlanName1,'')
OR
IsNull(cp.Description,'') <> IsNull(c.PlanName2,'')
)

SET @Count = @@ROWCOUNT
IF @Count > 0
BEGIN
SET @Status = 'Updated ' + Cast(@Count AS varchar(10)) + ' record(s) in ClientPlan.'
END
ELSE
BEGIN
SET @Status = 'No records were updated in Plan.'
END

SET @Status = 'Adding plan information to Plan table.'
INSERT INTO Statements..Plan (
ClientId,
ClientPlanId,
UserId,
PlanName,
Description
)
SELECT DISTINCT
@ClientId,
CPlanId,
@UserId,
PlanName1,
PlanName2
FROM
Census
WHERE
PlanId NOT IN (
SELECT DISTINCT
CPlanId
FROM
Statements..Plan
WHERE
ClientId = @ClientId
AND
ClientPlanId IS NOT NULL
)

SET @Count = @@ROWCOUNT
IF @Count > 0
BEGIN
SET @Status = 'Added ' + Cast(@Count AS varchar(10)) + ' record(s) to Plan.'
END
ELSE
BEGIN
SET @Status = 'No information was added Plan.'
END

SET NOCOUNT OFF
 
So how do i do multiple inserts and updates using this stored procedure...
 
Regards
Karen

View Replies !
Multiple Updates In Store Procedure?
I am a total newbie to SQL Server, but have a good idea about how things operate..

I have a "job" that runs multiple (10) update queries for me in different tables.

Can I create a stored procedure to do these so that I can make one call to them?

If not, how can I call the job to start external to MS SQL?

View Replies !
Making &&"incremental&&" Updates To A Data Warerhouse
We have a legacy database whose data needs to be included in our yet-to-be-built sql 2005 data warehouse.   Some of the tables don€™t have any natural candidates for a primary key. (Of course, we also need to add other data to the mix.)
 
Suppose we load the empty warehouse initially. In following loads we don€™t want to include those records that haven€™t changed from the first load  (€œduplicates€?) but we also don€™t want to delete the contents of the entire warehouse because of the load time.  Any ideas/best practices how to handle €œincremental updates€? to a warehouse would be appreciated.
 
TIA,
 
Bill

View Replies !
Help With Binding Textboxes In A Form To SQL Server 2000 Table (Keep Connection Open For Other User Updates)
I'm trying to move away from working in microsoft access and try and work with SQL Server.  I'm going to be storing around 50K records of data in a table within SQL server at first.  I tried using the visual studio.net Dataset control to create all my bound fields in the set, but what I noticed is the connection is not continually connected to the source.  I will have several users using this app, and each could be updating any record at any time, and I need and update to take affect on the server right away and the next time someones accesses that record will see the update.  What I have found out is that the DataSet created is only a copy of the Data at that moment and then the connection is closed, so no telling if anything was updated.  Now I tried making an ADO connection that is always connected and display the recordset in bound textboxes.  I can connect and create the recordset, but how do I bind the columns to the textboxes and make sure they are updated at the source when a change is made.  Below is the sample of how I'm connecting, please any help or new ideas would be greatly appreciated.  msgboxes at the bottom was for me to make sure I'm making the connection and seeing all the records.

 

 

Dim ObjConn As New ADODB.Connection

Dim ObjRS As New ADODB.Recordset

Dim countrr As Integer

Dim strRequest As String

With ObjConn

.ConnectionTimeout = 30

.CommandTimeout = 30

.Provider = "SQLOLEDB"

.ConnectionString = "Driver={SQL Native Client};Server=DV8110USTEST;Database=ALSQL;UID=AL;PWD=al;"

End With

ObjConn.Open()

strRequest = "SELECT * FROM dbo.DeskGroupings"

ObjRS.Open(strRequest, ObjConn, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockReadOnly)

Do While Not ObjRS.EOF

countrr = countrr + 1

ObjRS.MoveNext()

Loop

MsgBox(countrr)

MsgBox(ObjRS.RecordCount)

View Replies !
User Defined Data Type Used In Stored Procedure Parameters
I have several stored procedures with parameters that are defined withuser defined data types. The time it takes to run the procedures cantake 10 - 50 seconds depending on the procedure.If I change the parameter data types to the actual data type such asvarchar(10), etc., the stored procedure takes less that a second toreturn records. The user defined types are mostly varchar, but someothers such as int. They are all input type parameters.Any ideas on why the stored procedure would run much faster if notusing user defined types?Using SQL Server 2000.Thanks,DW

View Replies !
Can SSRS 2005 Handle Stored Procedures Or SQL Subqueries That Rreturn Rowsets Based On Multiple SQL Updates?
Hello,

I have a stored procedure that creates a temporary table, and then populates it using an INSERT and then a series of UPDATE statements. The procedure then returns the temporary table which will contain data in all of its columns.

When I call this procedure from SSRS 2005, the rowset returned contains data in only those columns that are populated by the INSERT statement. The columns that are set via the UPDATE statements are all empty. I read (in the Hitchhikers Guide to Reporting Services) that SSRS will only process the first rowset in a stored procedure that generates multiple rowsets. Is this true? Is this why SSRS does not retrieve data for the columns that are populated by the UPDATE statements?

Here is the stored procedure:

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-- File: sp_GetProgramsWatchedByDateRange.sql
-- Desc: Returns EDP program and related channel (i.e., provider) information from the IPTV Data warehouse.
--   Note that some of that data used by this procedure are obtained from the RMS_EPG database
--    which is created by an application (loadEPG) that loads the EPG data from a GLF format XML file.
-- Auth: H Hunsaker
-- Date: 11/07/2006

-- Example invocation
-- EXEC dbo.sp_GetProgramsWatchedByDateRange ...

-- Arguments/Parameters:

--    Parameter Name Type      Description
-- 3. StartDate   datetime     First date of reporting period
-- 4. EndDate   datetime     Last date of reporting period
--    TerseMode   bit       Return all columns? (1 = no, 0 = yes)
-- 5. AsXML    bit       Resultset format (0 = standard, 1 = XML)
-- 6. Debug    bit       Debug mode (0 = off, 1 = on). Currently disabled

IF OBJECT_ID (N'dbo.sp_GetProgramsWatchedByDateRange') IS NOT NULL
    DROP PROCEDURE dbo.sp_GetProgramsWatchedByDateRange
GO

CREATE PROCEDURE dbo.sp_GetProgramsWatchedByDateRange
      @StartDate datetime = NULL,
      @EndDate datetime = NULL,
      @TerseMode bit = 0,
      @AsXML bit = 0,
      @Debug bit = 0
AS
 --  Notes: Much of the program content (roles, flags, etc.) that we want is not stored in the IPTV data warehouse.
 --  So I am going to the RMS_EPG database to obtain that information.
 -- We will have to ensure that the 2 databases are generated at the same or a matching time
 --  in order to to ensure that all programID values in the data warehouse can be located in the RMS_EPG database.
 
 -- Debug code for testing
 -- DECLARE @StartDate datetime
 -- DECLARE @EndDate datetime
 -- DECLARE @TerseMode bit
 
 --SET @StartDate = NULL
 --SET @EndDate = NULL
 --SET @TerseMode = 1
 
 SET NOCOUNT ON 

 CREATE TABLE #programWatched
 (
  --IPTV device ID
  tdeviceId     uniqueidentifier NULL,
  taccountId     uniqueidentifier NULL,
  
  -- Basic program information
  tprogram    int     NULL,  -- programID from EPG XML, needed to access program data in the RMS_EPG db.
  tprogramId     uniqueidentifier NULL,  -- programID generated by IPTV
  tprogramTitle    varchar(150) NULL,
  tprogramEpisodeTitle  varchar(100) NULL,
  tprogramDescription   varchar(500) NULL,
  
  toriginDateTime   datetime  NULL,
  tduration    bigint   NULL,
  tprogramType   nvarchar(100) NULL,
  tchannelCallName  nvarchar(20) NULL,
  
  --Rating
  programMPAARating  varchar(50) NULL,
  programVCHIPRating  varchar(50) NULL,
  programMPAARatingVal smallint  NULL,
  programVChipRatingVal smallint  NULL,
  
  -- Categories
  programGenre   varchar(50) NULL,
  programCategory1  varchar(50) NULL,
  programCategory2  varchar(50) NULL,
  programCategory3  varchar(50) NULL,
  programCategory4  varchar(50) NULL,
  
  -- Roles  
  programActor1FirstName varchar(50) NULL,
  programActor1LastName varchar(50) NULL,
  programActor1   varchar(100) NULL,
  
  programActor2FirstName varchar(50) NULL,
  programActor2LastName varchar(50) NULL,
  programActor2   varchar(100) NULL,
  
  programActor3FirstName varchar(50) NULL,
  programActor3LastName varchar(50) NULL,
  programActor3   varchar(100) NULL,

  programActor4FirstName varchar(50) NULL,
  programActor4LastName varchar(50) NULL,
  programActor4   varchar(100) NULL,
  
  programActor5FirstName varchar(50) NULL,
  programActor5LastName varchar(50) NULL,
  programActor5   varchar(100) NULL,
  
  programActor6FirstName varchar(50) NULL,
  programActor6LastName varchar(50) NULL,
  programActor6   varchar(100) NULL,
  
  programActor7FirstName varchar(50) NULL,
  programActor7LastName varchar(50) NULL,
  programActor7   varchar(100) NULL,
  
  programActor8FirstName varchar(50) NULL,
  programActor8LastName varchar(50) NULL,
  programActor8   varchar(100) NULL,
  
  programDirectorFirstName varchar(50) NULL,
  programDirectorLastName  varchar(50) NULL,
  programDirector   varchar(100) NULL,
  
  programWriterFirstName varchar(50) NULL,
  programWriterLastName varchar(50) NULL,
  programWriter   varchar(100) NULL,
  
  programProducerFirstName varchar(50) NULL,
  programProducerLastName varchar(50) NULL,
  programProducer   varchar(100) NULL,
  
  -- Flags  
  ClosedCaption   bit NULL,
  InStereo    bit NULL,
  Repeats     bit NULL,
  New      bit NULL,
  Live     bit NULL,
  Taped     bit NULL,
  Subtitled    bit NULL,
  SAP      bit NULL,
  ThreeD     bit NULL,
  Letterbox    bit NULL,
  HDTV     bit NULL,
  Dolby     bit NULL,
  DVS      bit NULL,
  
  FlagOrdinalValue  smallint NULL,
  
  -- Channel
  tchannelId    int NULL,
  
  callLetters    varchar(20) NULL,
  displayName    varchar(50) NULL,
  type     varchar(50) NULL,
  networkAffiliation  varchar(50) NULL
 )
 
 -- I store the program watching data in a temp table because
 -- data from the VIL and the Sandbox that were used to test this procedure were either incomplete or invalid.
 -- Use of a temp table with a series of updates allow me more control over the result set.
 
 IF @StartDate IS NOT NULL AND @EndDate IS NOT NULL
  INSERT INTO #programWatched (
       tdeviceId,
       tprogramId,
       --tprogramTitle,
       --tprogramEpisodeTitle,
       toriginDateTime,
       tduration,
       --tprogramType,
       --tchannelCallName,

       ClosedCaption,
       InStereo,
       Repeats,
       New,
       Live,
       Taped,
       Subtitled,
       SAP,
       ThreeD,
       Letterbox,
       HDTV,
       Dolby,
       DVS
       )
  SELECT  pw.DeviceID,
    pw.programID,
    --epg.program,
    --epg.programTitle,
    --epg.programEpisodeTitle,
    pw.originTime AS 'When Watched',
    pw.Duration AS 'Duration Seconds',
    --epg.programType,
    --epg.channelCallName,

    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0  -- program flag values default to zero, as we do not want NULL values.

  FROM DW_EventClientProgramWatched pw
  WHERE programID IS NOT NULL AND programID != '00000000-0000-0000-0000-000000000000'  -- These values should not occur, but they did in the test system
    AND originTime BETWEEN @StartDate AND @EndDate
 ELSE
  INSERT INTO #programWatched (
       tdeviceId,
       tprogramId,
       --tprogramTitle,
       --tprogramEpisodeTitle,
       toriginDateTime,
       tduration,
       --tprogramType,
       --tchannelCallName,

       ClosedCaption,
       InStereo,
       Repeats,
       New,
       Live,
       Taped,
       Subtitled,
       SAP,
       ThreeD,
       Letterbox,
       HDTV,
       Dolby,
       DVS
       )
  SELECT  pw.DeviceID,
    pw.programID,
    --epg.program,
    --epg.programTitle,
    --epg.programEpisodeTitle,
    pw.originTime AS 'When Watched',
    pw.Duration AS 'Duration Seconds',
    --epg.programType,
    --epg.channelCallName,

    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0  -- program flag values default to zero, as we do not want NULL values.

  FROM DW_EventClientProgramWatched pw
  WHERE programID IS NOT NULL AND programID != '00000000-0000-0000-0000-000000000000'  -- These values should not occur, but they did in the test system

 -- AccountId/SubscriberId
 UPDATE #programWatched
 SET taccountId = (SELECT accountId
      FROM DW_BRDB_bm_device d
      WHERE d.deviceId = tdeviceId)
     
 -- program (this is the integer program ID stored in the EPG XML, not to be confused with the IPTV programId)
 -- a program can occur on multiple channels, so we filter channels where scheduleTime <= originTime <= scheculeTime + durationSecs
 UPDATE #programWatched
 SET tchannelCallName = (SELECT TOP 1 channelCallName
       FROM DW_EPG EPG
       WHERE tprogramId = EPG.programId AND toriginDateTime BETWEEN scheduleTime AND DATEADD(s, epg.durationSecs, epg.scheduleTime))

 UPDATE #programWatched
 SET tprogram =     (SELECT TOP 1 program FROM DW_EPG EPG WHERE tprogramId = EPG.programId AND tchannelCallName = channelCallName),
  tprogramTitle =   (SELECT TOP 1 programTitle FROM DW_EPG EPG WHERE tprogramId = EPG.programId AND tchannelCallName = channelCallName),
  tprogramEpisodeTitle =  (SELECT TOP 1 programEpisodeTitle FROM DW_EPG EPG WHERE tprogramId = EPG.programId AND tchannelCallName = channelCallName),
  tprogramType =    (SELECT TOP 1 programType FROM DW_EPG EPG WHERE tprogramId = EPG.programId AND tchannelCallName = channelCallName)
 
   -- Rating (otained from programValues, can also be obtained from programFlags)
 UPDATE #programWatched
 SET programMPAARating = (SELECT TOP 1 programValue
        FROM RMS_EPG..programValue pv
        WHERE tprogram = pv.programID AND pv.programValueTypeId = 9)
      
 UPDATE #programWatched
 SET programMPAARatingVal = CASE programMPAARating 
         WHEN 'G'  THEN 10
         WHEN 'PG'  THEN 25
         WHEN 'PG-13' THEN 30
         WHEN 'R'  THEN 35
         WHEN 'NC-17' THEN 50
         WHEN 'NRAO'  THEN 60
         WHEN 'NR'   THEN 0
         ELSE      0
        END
        
 UPDATE #programWatched
 SET programVChipRating = (SELECT TOP 1 programValue
        FROM RMS_EPG..programValue pv
        WHERE tprogram = pv.programID AND pv.programValueTypeId = 8)
       
 UPDATE #programWatched
 SET programVChipRatingVal = CASE programVChipRating
         WHEN 'TV-Y'  THEN 10
         WHEN 'TV-Y7' THEN 20
         WHEN 'TV-G'  THEN 35
         WHEN 'TV-PG' THEN 40
         WHEN 'TV-14' THEN 45
         WHEN 'TV-MA' THEN 60
         ELSE      0
        END     
       
   -- Genre
   UPDATE #programWatched
 SET programGenre = (SELECT TOP 1 programCategoryTypeValue
      FROM RMS_EPG..programCategory pc
      INNER JOIN RMS_EPG..programSubCategoryType psct ON psct.programSubCategoryTypeId = pc.programCategoryId
      INNER JOIN RMS_EPG..programCategoryType pct ON pct.programCategoryTypeId = psct.programCategoryTypeId
      WHERE tprogram = pc.programID)
      
   -- Categories
 UPDATE #programWatched
 SET programCategory1 = (SELECT TOP 1 programSubCategoryTypeValue
       FROM RMS_EPG..programCategory pc
       INNER JOIN RMS_EPG..programSubCategoryType pct ON pct.programSubCategoryTypeId = pc.programCategoryId
       WHERE tprogram = pc.programID)

 UPDATE #programWatched
 SET programCategory2 = (SELECT TOP 1 programSubCategoryTypeValue
       FROM RMS_EPG..programCategory pc
       INNER JOIN RMS_EPG..programSubCategoryType pct ON pct.programSubCategoryTypeId = pc.programCategoryId
       WHERE tprogram = pc.programID AND programSubCategoryTypeValue NOT IN (programCategory1))
       
 UPDATE #programWatched
 SET programCategory3 = (SELECT TOP 1 programSubCategoryTypeValue
       FROM RMS_EPG..programCategory pc
       INNER JOIN RMS_EPG..programSubCategoryType pct ON pct.programSubCategoryTypeId = pc.programCategoryId
       WHERE tprogram = pc.programID AND programSubCategoryTypeValue NOT IN (programCategory1, programCategory2))
       
 UPDATE #programWatched
 SET programCategory4 = (SELECT TOP 1 programSubCategoryTypeValue
       FROM RMS_EPG..programCategory pc
       INNER JOIN RMS_EPG..programSubCategoryType pct ON pct.programSubCategoryTypeId = pc.programCategoryId
       WHERE tprogram = pc.programID AND programSubCategoryTypeValue NOT IN (programCategory1, programCategory2, programCategory3))

   -- Roles
   UPDATE #programWatched
 SET programDirectorFirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 2)

 UPDATE #programWatched
 SET programDirectorLastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 2)
         
 UPDATE #programWatched
 SET programDirector = programDirectorLastName + ' , ' + programDirectorFirstName
       
 UPDATE #programWatched
 SET programWriterFirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 7)
         
 UPDATE #programWatched
 SET programWriterLastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 7)
       
 UPDATE #programWatched
 SET programWriter = programWriterLastName + ' , ' + programWriterFirstName
       
 UPDATE #programWatched
 SET programProducerFirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 6)
         
 UPDATE #programWatched
 SET programProducerLastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 6)
       
 UPDATE #programWatched
 SET programProducer = programProducerLastName + ' , ' + programProducerFirstName
       
 UPDATE #programWatched
 SET programActor1FirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1)
 UPDATE #programWatched
 SET programActor1LastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1)
         
 UPDATE #programWatched
 SET programActor1 = programActor1LastName + ' , ' + programActor1FirstName
         
 UPDATE #programWatched
 SET programActor2FirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
         AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName))
         
 UPDATE #programWatched
 SET programActor2LastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
         AND programRoleLastName NOT IN (programActor1LastName) AND programRoleLastName NOT IN (programActor1LastName))
         
 UPDATE #programWatched
 SET programActor2 = programActor2LastName + ' , ' + programActor2FirstName
         
 UPDATE #programWatched
 SET programActor3FirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName))

 UPDATE #programWatched
 SET programActor3LastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleLastName NOT IN (programActor1LastName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleLastName NOT IN (programActor2LastName) AND programRoleLastName NOT IN (programActor2LastName))
           
 UPDATE #programWatched
 SET programActor3 = programActor3LastName + ' , ' + programActor3FirstName
         
 UPDATE #programWatched
 SET programActor4FirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName))

 UPDATE #programWatched
 SET programActor4LastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName))

 UPDATE #programWatched
 SET programActor4 = programActor4LastName + ' , ' + programActor4FirstName
         
 UPDATE #programWatched
 SET programActor5FirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
           AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName))

 UPDATE #programWatched
 SET programActor5LastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
           AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName))
         

 UPDATE #programWatched
 SET programActor5 = programActor5LastName + ' , ' + programActor5FirstName
         
 UPDATE #programWatched
 SET programActor6FirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
           AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
           AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName))

 UPDATE #programWatched
 SET programActor6LastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
           AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
           AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName))
       
 UPDATE #programWatched
 SET programActor6 = programActor6LastName + ' , ' + programActor6FirstName
         
 UPDATE #programWatched
 SET programActor7FirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
           AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
           AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName)
           AND programRoleFirstName NOT IN (programActor6FirstName) AND programRoleLastName NOT IN (programActor6LastName))

 UPDATE #programWatched
 SET programActor7LastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
           AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
           AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName)
           AND programRoleFirstName NOT IN (programActor6FirstName) AND programRoleLastName NOT IN (programActor6LastName))

 UPDATE #programWatched
 SET programActor7 = programActor7LastName + ' , ' + programActor7FirstName
      
 UPDATE #programWatched
 SET programActor8FirstName = (SELECT TOP 1 programRoleFirstName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
           AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
           AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName)
           AND programRoleFirstName NOT IN (programActor6FirstName) AND programRoleLastName NOT IN (programActor6LastName)           
           AND programRoleFirstName NOT IN (programActor7FirstName) AND programRoleLastName NOT IN (programActor7LastName))


 UPDATE #programWatched
 SET programActor8LastName = (SELECT TOP 1 programRoleLastName
         FROM RMS_EPG..programRoleName prn
         INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
         WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
           AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
           AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
           AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
           AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
           AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName)
           AND programRoleFirstName NOT IN (programActor6FirstName) AND programRoleLastName NOT IN (programActor6LastName)
           AND programRoleFirstName NOT IN (programActor7FirstName) AND programRoleLastName NOT IN (programActor7LastName))

 UPDATE #programWatched
 SET programActor8 = programActor8LastName + ' , ' + programActor8FirstName

 -- Channel (provider) Call Letters, Display Name and Type
 -- Is this correct? Should we get the channelId from the schedule table?
 -- Is this efficient? View execution plan

 UPDATE #programWatched
 SET tchannelId = (SELECT TOP 1 c.channelId
      FROM RMS_EPG..channel c
      INNER JOIN RMS_EPG..schedule s on s.channelID = c.channelID
      WHERE s.programId = tprogram)
      
 UPDATE #programWatched
 SET callLetters = (SELECT TOP 1 c.channelCallLetters
      FROM RMS_EPG..channel c
      INNER JOIN RMS_EPG..schedule s on s.channelID = c.channelID
      WHERE s.programId = tprogram and s.channelId = tchannelId)

 UPDATE #programWatched
 SET displayName = (SELECT TOP 1 c.channelDisplayName
      FROM RMS_EPG..channel c
      JOIN RMS_EPG..schedule s on s.channelID = c.channelID
      WHERE s.programId = tprogram and s.channelId = tchannelId)

 UPDATE #programWatched
 SET type = (SELECT TOP 1 c.channelType
    FROM RMS_EPG..channel c
    INNER JOIN RMS_EPG..schedule s on s.channelID = c.channelID
    WHERE s.programId = tprogram and s.channelId = tchannelId)

 UPDATE #programWatched
 SET networkAffiliation = (SELECT TOP 1 c.channelNetworkAffiliation
        FROM RMS_EPG..channel c
        INNER JOIN RMS_EPG..schedule s on s.channelID = c.channelID
        WHERE s.programId = tprogram and s.channelId = tchannelId)

 IF @TerseMode = 0
  SELECT *
  FROM #programWatched
  ORDER BY toriginDateTime
 ELSE
  -- Get only Genre, title, show date/time, rating, call letters
  SELECT tDeviceId, tprogramTitle, tprogramEpisodeTitle, programGenre, toriginDateTime, programMPAARating, programVCHIPRating, tchannelCallName
  FROM #programWatched
  ORDER BY toriginDateTime
  
 DROP TABLE #programWatched

 SET NOCOUNT OFF

GO

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

I also tried a query that populates some of its columns via subqueries. The query works fine when executed by the SQL Sevrer Query Analyzer,
meaning that all columns contain values, but when executed from SSRS, the columns that are poulated by the subqueries are empty, and only the columns that are not set by subqueries contain values:

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

SELECT  PW.DeviceID,
              PW.originTime AS 'When Watched',
              PW.programID,
              PW.Duration AS 'Duration Seconds',
  
              (SELECT TOP 1 programTitle FROM DW_EPG WHERE DW_EPG.programId = PW.programId AND PW.originTime BETWEEN DW_EPG.scheduleTime
                         AND DATEADD(second, durationSecs, DW_EPG.scheduleTime)) AS Title,

              (SELECT TOP 1 program FROM DW_EPG WHERE DW_EPG.programId = PW.programId AND PW.originTime BETWEEN DW_EPG.scheduleTime AND
                        DATEADD(second, durationSecs, DW_EPG.scheduleTime)) As program,
    
               (SELECT TOP 1 programCategoryTypeValue
                FROM RMS_EPG..programCategory PC
                INNER JOIN RMS_EPG..programSubCategoryType PSCT ON psct.programSubCategoryTypeId = PC.programCategoryId
                INNER JOIN RMS_EPG..programCategoryType PCT ON PCT.programCategoryTypeId = PSCT.programCategoryTypeId
                WHERE PC.programID = (SELECT TOP 1 program FROM DW_EPG WHERE DW_EPG.programId = PW.programId AND PW.originTime BETWEEN
                                DW_EPG.scheduleTime AND DATEADD(second, durationSecs, DW_EPG.scheduleTime))) AS Genre,
     
               (SELECT TOP 1 programSubCategoryTypeValue
                FROM RMS_EPG..programCategory PC
                INNER JOIN RMS_EPG..programSubCategoryType PSCT ON psct.programSubCategoryTypeId = PC.programCategoryId
                INNER JOIN RMS_EPG..programCategoryType PCT ON PCT.programCategoryTypeId = PSCT.programCategoryTypeId
                WHERE PC.programID = (SELECT TOP 1 program FROM DW_EPG WHERE DW_EPG.programId = PW.programId AND PW.originTime
                               BETWEEN DW_EPG.scheduleTime AND DATEADD(second, durationSecs, DW_EPG.scheduleTime))) AS Category
    
FROM DW_EventClientProgramWatched PW
ORDER BY DeviceId, programId, originTime

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Any help is appreciated

 

View Replies !
Firing A Java Application From Stored Procedure
Hey all,
I've got a question and after doing some research I've found only a vague reference but no clear answer.

I have a java app that will be passing parameters to my stored procedure. I'll grab the requested info from the tables but instead of sending it back to the java app that sent the request, I need to send it to a "different" java app (the second java app will not be running at the time).

Can someone point me to a good source for executing java applications from a stored procedure?

Thanks in advance ...
tam

View Replies !
How Do I Call A Stored Procedure To Insert Data In SQL Server In SSIS Data Flow Task
 

I need to call a stored procedure to insert data into a table in SQL Server from SSIS data flow task.
I am currently trying to use OLe Db Destination, but I am not sure how to map inputs to OLE DB Destination to my stored procedure insert.
Thanks

View Replies !
Firing An Append Query(stored Procedure) On The First Of Very Month
I need several stored procedures to fire on the 1st of every month. I was told my another developer I can possibly use SQL sever agent.

Any ideas????

View Replies !
Receiving Queue Stops Firing Stored Procedure
 

I've set up a Service Broker and it was working fine.
 
All of a sudden each time I switch on my computer it's not working anymore.
 
I have to drop the services, queues, contract and messages and create them again.
 
Then it works again until I shutdown my computer.  When I start it again it's not working.
 
Any suggestion on how to fix this?
 
Thank you

View Replies !
User 'Unknown User' Could Not Execute Stored Procedure - Debugging Stored Procedure Using Visual Studio .net
Hi all,

 

I am trying to debug stored procedure using visual studio. I right click on connection and checked 'Allow SQL/CLR debugging' .. the store procedure is not local and is on sql server.

 

Whenever I tried to right click stored procedure and select step into store procedure> i get following error

 

"User 'Unknown user' could not execute stored procedure 'master.dbo.sp_enable_sql_debug' on SQL server XXXXX. Click Help for more information"

 

I am not sure what needs to be done on sql server side

 

We tried to search for sp_enable_sql_debug but I could not find this stored procedure under master.

Some web page I came accross says that "I must have an administratorial rights to debug" but I am not sure what does that mean?

 

Please advise..

Thank You

View Replies !
Trigger Firing And Not Firing
I have a trigger on a table that just updates a last_modified_date and this works fine on our production server. Now I have to update some data and I do not want the trigger to fire. I cannot disable or drop the trigger because the productions systems needs the trigger. Anyone an idea of how to solve this problem?

View Replies !
Creating A Stored Procedure That Will Summarize Data In A Table Into A Table Reflecting Period Data Using An Array Type Field
I am attempting to create a stored procedure that will launch at report runtime to summarize data in a table into a table that will reflect period data using an array type field.  I know how to execute one line but I am not sure how to run the script so that it not only summarizes the data below but also creates and drops the table.
 
Any help would be greatly appreciated.
 
Current Table
 
Project   |  Task      | Category |  Fiscal Year | Fiscal Month | Total Hours
---------------------------------------------------------------------------------------------------------
Proj 1     |  Task 1   | Cat 1      |  2007           |  01                |   40
Proj 1     |  Task 1   | Cat 2      |  2007           |  02                |   20
Proj 1     |  Task 1   | Cat 3      |  2007           |  03                |   35
Proj 1     |  Task 1   | Cat 1      |  2008           |  01                |   40
Proj 1     |  Task 1   | Cat 2      |  2008           |  02                |   40
Proj 1     |  Task 1   | Cat 3      |  2008           |  03                |   40
 
Proposed Table
 
Project   | Task      | Category   | Fiscal Month 01   | Fiscal Month 02   | Fiscal Month 03 | Fiscal Year
---------------------------------------------------------------------------------------------------------------------------------------------------
Proj 1     |  Task 1  | Cat 1        |          40              |           0               |         0              |    2007
Proj 1     |  Task 1  | Cat 2        |           0               |         20               |         0              |    2007Proj 1     |  Task 1  | Cat 3        |           0               |           0               |        35             |    2007
Proj 1     |  Task 1  | Cat 1        |         40               |           0               |          0             |    2008

Proj 1     |  Task 1  | Cat 2        |           0               |         40               |          0             |    2008
Proj 1     |  Task 1  | Cat 3        |           0               |           0               |        40             |    2008
 
Thanks,
Mike Misera

View Replies !
1 To Many Updates
I have a web form that collects details on books (as an example), and in that form is a checkboxlist that displays an entry for each potential author in the database (as an example).

The user can obviously tick as many authors as they want to represent Authors of the book. The ticked entries form the entries in the BooksToAuthors table which only has BookID and AuthorID columns.

I have a number of questions:

How do I take what is in the CheckBoxList to the database and how does this relate to Stored Procedures?

Do I fill the checkbox selections into an Array? How do I get these 'many items' to a Stored Procedure that runs a transaction to put the book in and then the many rows in AuthorsToBooks.

What is being passed? Can you pass an array or something to a stored procedure?

View Replies !
Updates In DTS
I am attempting to update one of my Sql Server tables with data from an Access database table. I understand that you can do an update rather than an insert, but I cannot figure out how do so. Can anyone help?

View Replies !
MS Updates?
I have an SQL 2005 STD server, full install, that we use to run SQL and reporting services.  When I run Microsoft Update, it shows updates for Visual Studio 2005 SP1 and MS Office 2003 SP3.  The server does have MS Office 2003 web components installed, installed as part of the initial SQL server install, but not the MS Office suite software.  It also has loaded the reporting services version of Visual studio 2005 that installs with reporting services, but not the entire version of Visual Studio 2005.  Should I install these service pack updates?  Is there any benifit?

View Replies !
37 Updates In One
okay, so i have about 37 different updates i need to do to a table that is rather large (71million) and has no indexes. i know it's gunna table scan, and honestly, i'm not really worried about that. my question is, is there a way up squeeze all of these updates into one?

here is what i was going to do, but each one will take about an hour to run... (here are 5 of the 37 updates, but they are all basically the same concept)


update t1 set books_music='' from mailorder t1 where books_music is null
update t1 set Car_Buff='' from mailorder t1 where Car_Buff is null
update t1 set Childrens_Items_Buyers='' from mailorder t1 where Childrens_Items_Buyers is null
update t1 set Computer='' from mailorder t1 where Computer is null
update t1 set Crafts_Sewing='' from mailorder t1 where Crafts_Sewing is null




in FoxSlow (foxpro) i could just do something like this:


do while !eof()
replace books_music with '' for books_music=null
replace car_buff with '' for car_buff=null
skip
enddo

View Replies !
Need Advice On Updates
Hi, I just started learning ASP.NET this week and have watched a mountain of videos from this website which has helped me alot However I have been stuck on a problem for 2 days now. I have created an SQL database with the Following 2 tables: USERS                        COMPUTERSUserid                           Computerid   firstname                       Useridsecondname                  Manufacturer                                    Model I have made a relationship between the 2 tables. I then created a dataset with the following query:SELECT COMPUTERS.Computer_ID, COMPUTERS.Manufacturer, COMPUTERS.Model, USERS.First_Name, USERS.Last_Name FROM COMPUTERS INNER JOIN USERS ON COMPUTERS.User_ID = USERS.User_ID I however do not get the option in my grid view when i output this data, to UPDATE. The best i have found from google is that i need to use subqueries and not innerjoins but i just cant seem to get my head around them, please help as i feel my head may just explode if i think about this or try any more ways to get this to work :D 

View Replies !
2 Updates In The Same Querry!
Hi! I 'd like to update the database..I 'd like to update the same field, the first update would set all to 'No' and the second update woyuld set specific records to 'Yes':
1)  "Update tblDept SET IsTop ='No'
2) "Update tblDept  SET IsTop = 'Yes'  WHERE id = 200 "
Cheers!

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved