Havin Trouble Inserting Records To A Table.. Update Works Fine
Hi..
I am getting a xml stream of data and putting it to a object and then calling a big sproc to insert or update data in many tables across my database... But there is one Table that i am having trouble inserting it.. But if i run an update it works fine... This my code for that part of the sproc..
IF Exists(
SELECT
*
FROM
PlanEligibility
WHERE
PlanId = @PlanId
) BEGIN
UPDATE
PlanEligibility
SET
LengthOfService = Case When @PD_EmployeeContribution = 0 Then @rsLengthOfServicePS
ELSE @rsLengthOfService END,
EligibilityAge = CASE When @PD_EmployeeContribution = 0 Then @EligibilityAgePS Else @EligibilityAge End,
EntryDates = @EntryDates,
EligiDifferentRequirementsMatch = Case When @PD_EmployeeContribution = 0 Then 0
When @PD_EmployeeContribution = 1 and @PD_EmployerContribution = 0 then 0 Else 1 END, --@CompMatchM,
LengthOfServiceMatch = CASE When @MCompanyMatch = 0 Then @rsLengthOfServicePs ELSE @rsLengthOfServiceMatch END,
EligibilityAgeMatch = CASE When @MCompanyMatch = 0 Then @EligibilityAgePS ELSE @EligibilityAgeMatch END,
OtherEmployeeExclusions = @OtherEmployeeExclusions
WHERE
PlanId = @PlanId
END
ELSE BEGIN
INSERT INTO PlanEligibility
(
PlanId,
LengthOfService,
EligibilityAge,
EntryDates,
EligiDifferentRequirementsMatch,
LengthOfServiceMatch,
EligibilityAgeMatch,
OtherEmployeeExclusions
)
VALUES
(
@PlanId,
Case When @PD_EmployeeContribution = 0 Then @rsLengthOfServicePS
ELSE @rsLengthOfService END,--@rsLengthOfService,
CASE When @PD_EmployeeContribution = 0 Then @EligibilityAgePS Else @EligibilityAge End, --@EligibilityAge,
@EntryDates,
Case When @PD_EmployeeContribution = 0 Then 0
When @PD_EmployeeContribution = 1 and @PD_EmployerContribution = 0 then 0 Else 1 END, --having trouble here
CASE When @MCompanyMatch = 0 Then @rsLengthOfServicePs ELSE @rsLengthOfServiceMatch END,
CASE When @MCompanyMatch = 0 Then @EligibilityAgePS ELSE @EligibilityAgeMatch END, --EligibilityAgeMatch,@EligibilityAgeMatch,
@OtherEmployeeExclusions
)
END
Any help will be appreciated..
Regards,
Karen
View Complete Forum Thread with Replies
Related Forum Messages:
- SQL 2000 Partitioned View Works Fine, But CURSOR With FOR UPDATE Fails To Declare
- Table Visibility Not Functioning Correctly On Server, Works Fine In Visual Studio
-
How To Automatically Create New Records In A Foreign Table When Inserting Records In A Primary Table.
- Sql Job Fails But When Run Outside Works Fine
- Transfer Problems For 6.5 Next Week Works Fine
- 32 Bit DTExec Fails While 64 Bit Works Fine On 64 Bit Machine
- Job Doesn't Work But Package Works Fine
-
Remote Connection Tests Fine, But Nothing Works On The Page Itself.
-
DTS Job Failing Execution When Scheduled, Works Fine Manually.
- Query Works Fine Outside Union, But Doesn't Work .. .
- Using Symmetric Key Problem With Encryption, Decryption Works Fine
- Slow Query....drop Index Works Fine!!!!!
- Report Works Fine Stand Alone, But Fails When Used As Subreport
- Multivalue Works Fine In The Sproc But Not In Bids Or Reportserver
-
Problems Publishing My Personal Website - Works Fine Locally!
- Long Running Query In SQL 2005 But Works Fine In SQL 2000
- Stored Procedure Works Fine, But Doesnt Preview? (Beginner)
- Works Fine In Designer But When I Load The Report It Doesn't Work
- Permission Issue With Tempdb Works Fine In SQL2000 But Not SQL2005
-
Trying To Save Editted Textbox Value In Table But Original Value Saves Instead - Trouble With Table Update Query
- Works Fine Inside BI Dev. Studio, But Fails When Scheduling It In SQL Server 2005.
- Update Table From MS2005 To Oracle 9.2 - No Solution Works For Me
-
Inserting Multiple Records To A Table
- Retrieving Records And Inserting Into Table
- Xp_sendmail: Failed With Mail Error 0x80040111 It Works Fine When You Do A Test From Enterprise Manager
- Selecting Records From One Column In A Table And Inserting..
- RESTORE FILELIST Is Terminating Abnormally Error When Running A DTS Package In SQL 2005. Works Fine In SQL 2000
- Trouble With Adventure Works
- Update Table Lastrow Before Inserting
-
SQL SERVER ACCESS DENIED!! BUT Everything Works On MSDE And Works SHOWING RECORDS ON SQL SERVER!! PLEASE HELP
- How To Fine A Hole In A Records?
- OR Works Fine, When I Add AND Things Go Wrong (was &"Help With Simple Query&")
- Sql Report Works Fine On Internal Servers - Hosed On External Servers - Need Some Help
- SQL Server VARCHAR(MAX) Column Returns Error While Inserting Records Into Table(ODBC Driver: SQL Native Client)
- Update Table From Old Records
- Update All The Records Of A Table On A Condition
-
Trouble Inserting Values From Radiobuttons
-
Unable To Update Or Delete SQL Table Records
-
How To Update One Column To Be The Same For All Records In Database Table?
- Trouble With Update Trigger Modifying Table Which Fired Trigger
- SQL Update One Table With Records In Another Table
- Update Records From One Table To Another Table
- MS Access Back-end Works Fine, But SQL Server Back End NOT Working For Access Project
- Insert / Update In Master Table And Also Save A History Of Changed Records : Using Data Flow/simple Sql Queries
- Select Records Between Dates - Query Works In VS 2005 But It Doesn't In Asp 3
-
Inserting Data Into Two Tables (Getting ID From Table 1 And Inserting Into Table 2)
- I Want To Transfer ONLY New Records AND Update Any Modified Records From Oracle Into SQL Server Using DTS
-
Update Statement Works Ok But No Result
-
Dateadd Update Works But Adds 2 Or 3 Yrs-not 1
- SELECT Works But UPDATE Fails. ?
- One Table Is Ultra Slow At Being Copied, Others Are Fine
SQL 2000 Partitioned View Works Fine, But CURSOR With FOR UPDATE Fails To Declare
This one has me stumped. I created an updateable partioned view of a very large table. Now I get an error when I attempt to declare a CURSOR that SELECTs from the view, and a FOR UPDATE argument is in the declaration. There error generated is: Server: Msg 16957, Level 16, State 4, Line 3 FOR UPDATE cannot be specified on a READ ONLY cursor Here is the cursor declaration: declare some_cursor CURSOR for select * from part_view FOR UPDATE Any ideas, guys? Thanks in advance for knocking your head against this one. PS: Since I tested the updateability of the view there are no issues with primary keys, uniqueness, or indexes missing. Also, unfortunately, the dreaded cursor is requried, so set based alternatives are not an option - it's from within Peoplesoft.
View Replies !
Table Visibility Not Functioning Correctly On Server, Works Fine In Visual Studio
I have a report problem. I'm using a parameter to dynamically control visibility for two tables. If the parameter is set to one value, I want to switch one of the tables to invisible, if the parameter is set to another, I want the other table to be invisible instead. This all works fine in Visual Studio. When I publish it to my report server, the visibility controls no longer function and both tables always display. Any ideas here? I'm running 2005, SP2 CTP.
View Replies !
How To Automatically Create New Records In A Foreign Table When Inserting Records In A Primary Table.
Ok, I'm really new at this, but I am looking for a way to automatically insert new records into tables. I have one primary table with a primary key id that is automatically generated on insert and 3 other tables that have foreign keys pointing to the primary key. Is there a way to automatically create new records in the foreign tables that will have the new id? Would this be a job for a trigger, stored procedure? I admit I haven't studied up on those yet--I am learning things as I need them. Thanks.
View Replies !
Sql Job Fails But When Run Outside Works Fine
Hi.. I am stuck at a very awkward place. I have created one package which uses an oracle view as its source for data transfer the problem is when i run the package through dtexec it works fine but when i try to schedule it I get the following error Error: 2008-03-24 13:52:40.22 Code: 0xC0202009 Source: pk_BMR_FEED_oracle Connection manager "Conn_BMR" Description: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005. An OLE DB record is available. Source: "Microsoft OLE DB Provider for Oracle" Hresult: 0x80004005 Description: "Oracle client and networking components were not found. These components are supplied by Oracle Corporation and are part of the Oracle Version 7.3.3 or later client software installation. Provider is unable to function until these components are installed.". I am able to run the package outside the sql job and also connect to the oracle. I have oracle 9i client installed on the server and sql server is 2005. Any help would really be appreciated..
View Replies !
Transfer Problems For 6.5 Next Week Works Fine
I have set up transfer of database which takes 6 hrs each saturday Type--- CMDeXEC last saturday it tooks just 7 mins and showed this error and did not coplete 2004/0619 4:00:18:42-spid14-Warning OPEN OBJECTS parameter too low 2004/0619 4:00:18:45-spit14-attempt was made to free up descriptors in localdes() 2004/0619 4:00:18:45-spid14-Run sp_configure to increase parameter value 2004/0619 4:00:19:95-spid14-Warning OPEN OBJECTS parameter too low 2004/0619 4:00:19:95-spit14-attempt was made to free up descriptors in localdes() 2004/0619 4:00:19:95-spid14-Run sp_configure to increase parameter value OriginalTransfered Data Size 19000(max 28105 mb)18640(max 18640) Log Size 4000(13105 mb)4640 (max 4640) Data Physical 18.5 gb18.5 gb logPhysical 3.90 g b4.88 gb looks like my data and log size should be increased correct if yes how to do that????? if worked this week fine (6 hrs )
View Replies !
32 Bit DTExec Fails While 64 Bit Works Fine On 64 Bit Machine
Hi, I am executing a SSIS package using dtexec. 64 bit version of dtexec works fine. But when i use 32 bit version of dtexec, it fails. i have local admin rights. Following is error description. Please help. Microsoft (R) SQL Server Execute Package Utility Version 9.00.1399.06 for 32-bit Copyright (C) Microsoft Corp 1984-2005. All rights reserved. Started: 9:24:30 AM Error: 2008-03-18 09:24:32.54 Code: 0xC0202009 Source: IMALCRM Connection manager "IMAL SRC" Description: An OLE DB error has occurred. Error code: 0x800703E6. An OLE DB record is available. Source: "Microsoft OLE DB Service Components" H result: 0x800703E6 Description: "Invalid access to memory location.". End Error Error: 2008-03-18 09:24:32.54 Code: 0xC020801C Source: Load Fund Detail V_FUND_DETAIL [16] Description: The AcquireConnection method call to the connection manager "IMA L SRC" failed with error code 0xC0202009. End Error Error: 2008-03-18 09:24:32.54 Code: 0xC0047017 Source: Load Fund Detail DTS.Pipeline Description: component "V_FUND_DETAIL" (16) failed validation and returned er ror code 0xC020801C. End Error Error: 2008-03-18 09:24:32.54 Code: 0xC004700C Source: Load Fund Detail DTS.Pipeline Description: One or more component failed validation. End Error Error: 2008-03-18 09:24:32.54 Code: 0xC0024107 Source: Load Fund Detail Description: There were errors during task validation. End Error DTExec: The package execution returned DTSER_FAILURE (1). Started: 9:24:30 AM Finished: 9:24:32 AM Elapsed: 2.078 seconds
View Replies !
Job Doesn't Work But Package Works Fine
hi, I have many jobs on sql 05 and all work but one. This one writes to an Access DB on the same server as SQL. The package works fine. But when executed in the context of the SQL Agent job, it fails. Jobs that write to a text file work fine. The Access DB has no password required. By the way, that job in sql 2000 worked fine. Any ideas?
View Replies !
Remote Connection Tests Fine, But Nothing Works On The Page Itself.
If this post belongs somewhere else I appologize. I have spent several days trying to solve this problem with no luck. My site is online. Hosted at NeikoHosting. I can connect to the database remotely when adding a datacontrol. It tests fine. But when running the page it won't connect. Even if I go in and change the Web.Config connection string to a local Data Source provided to me by Neiko, it still won't work. It just won't connect. Here are the two connection strings in the Web.Config, minus my login info: Only the remote string will pass testing. Neither works on the site. <add name="yourchurchmychurchDBConnectionString" connectionString="Data Source=MSSQL2K-A;Initial Catalog=yourchurchmychurchDB;Persist Security Info=True;User ID=me;Password=pwd" providerName="System.Data.SqlClient" /> <add name="yourchurchmychurchDBConnectionString2" connectionString="Data Source=66.103.238.206;Initial Catalog=yourchurchmychurchDB;Persist Security Info=True;User ID=me;Password=pwd" providerName="System.Data.SqlClient" /> Here is the stack trace, if that helps. [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.OleDb.OleDbException: [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [OleDbException (0x80004005): [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.] System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) +1131233 System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) +53 System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) +27 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +47 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +105 System.Data.OleDb.OleDbConnection.Open() +37 System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +121 System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +137 System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable) +83 System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1770 System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +17 System.Web.UI.WebControls.DataBoundControl.PerformSelect() +149 System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +70 System.Web.UI.WebControls.FormView.DataBind() +4 System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82 System.Web.UI.WebControls.FormView.EnsureDataBound() +163 System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +69 System.Web.UI.Control.EnsureChildControls() +87 System.Web.UI.Control.PreRenderRecursiveInternal() +50 System.Web.UI.Control.PreRenderRecursiveInternal() +170 System.Web.UI.Control.PreRenderRecursiveInternal() +170 System.Web.UI.Control.PreRenderRecursiveInternal() +170 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2041 So....... HELP!!!! Thank you!
View Replies !
DTS Job Failing Execution When Scheduled, Works Fine Manually.
My DTS Package work fine if I Execute it manually, but I need to do it automatically just after midnight. I defined my schedule and made sure the job was present in the SQL Server Agent>Jobs, but it fails and the Job History shows the following error: DTSRun: Loading... DTSRun: Executing... DTSRun OnStart: DTSStep_DTSDataPumpTask_1 DTSRun OnError: DTSStep_DTSDataPumpTask_1, Error = -2147467259 (80004005) Error string: [Microsoft][ODBC Microsoft Access Driver] Cannot start your application. The workgroup information file is missing or opened exclusively by another user. Error source: Microsoft OLE DB Provider for ODBC Drivers Help file: Help context: 0 Error Detail Records: Error: -2147467259 (80004005); Provider Error: 1901 (76D) Error string: [Microsoft][ODBC Microsoft Access Driver] Cannot start your application. The workgroup information file is missing or opened exclusively by another user. Error source: Microsoft OLE DB Provider for ODBC Drivers Help file: Help context: 0 DTSRun OnFinish: DTSStep_DTSDataPumpTask_1 DTSRun: Package execution complete. Process Exit Code 1. The step failed. Help!!!
View Replies !
Query Works Fine Outside Union, But Doesn't Work .. .
hi all I have the following query which works fine when it's executed as a single query. but when i union the result of this query with other queries, it returns a different set of data. any one know why that might be the case?? select top 100 max(contact._id) "_id", max(old_trans.date) "callback_date", 7 "priority", max(old_trans.date) "recency", count(*) "frequency" --contact._id, contact.callback_date from topcat.class_contact contact inner join topcat.MMTRANS$ old_trans on contact.phone_num = old_trans.phone where contact.phone_num is not null and contact.status = 'New Contact' group by contact._id order by "recency" desc, "frequency" desc i've included the union query here for completeness of the question begin declare @current_date datetime set @current_date = GETDATE() select top 100 _id, callback_date, priority, recency, frequency from ( ( select top 10 _id, callback_date, 10 priority, @current_date recency, 1 frequency --, DATEPART(hour, callback_date) "hour", DATEPART(minute, callback_date) "min" from topcat.class_contact where status ='callback' and (DATEPART(year, callback_date) <= DATEPART(year, @current_date)) and (DATEPART(dayofyear, callback_date) <= DATEPART(dayofyear, @current_date)) -- all call backs within that hour will be returned and (DATEPART(hour, callback_date) <= DATEPART(hour, @current_date)) and (DATEPART(hour, callback_date) <> 0) order by callback_date asc --order by priority desc, DATEPART(hour, callback_date) asc, DATEPART(minute, callback_date) asc, callback_date asc ) union ( select top 10 _id, callback_date, 9 priority, @current_date recency, 1 frequency from topcat.class_contact where status = 'callback' and callback_date is not null and (DATEPART(year, callback_date) <= DATEPART(year, @current_date)) and (DATEPART(dayofyear, callback_date) <= DATEPART(dayofyear, @current_date)) and (DATEPART(hour, callback_date) <= DATEPART(hour, @current_date)) and (DATEPART(hour, callback_date) = 0) order by callback_date asc ) union ( select top 10 _id, callback_date, 8 priority, @current_date recency, 1 frequency from topcat.class_contact where status = 'No Connect' and callback_date is not null and (DATEPART(year, callback_date) <= DATEPART(year, @current_date)) and (DATEPART(dayofyear, callback_date) <= DATEPART(dayofyear, @current_date)) and (DATEPART(hour, callback_date) <= DATEPART(hour, @current_date)) order by callback_date asc ) union ( select top 100 max(contact._id) "_id", max(old_trans.date) "callback_date", 7 "priority", max(old_trans.date) "recency", count(*) "frequency" --contact._id, contact.callback_date from topcat.class_contact contact inner join topcat.MMTRANS$ old_trans on contact.phone_num = old_trans.phone where contact.phone_num is not null and contact.status = 'New Contact' group by contact._id order by "recency" desc, "frequency" desc ) ) contact_queue order by priority desc, recency desc, callback_date asc, frequency desc end
View Replies !
Using Symmetric Key Problem With Encryption, Decryption Works Fine
Hey I had a table with a column of data encrypted in a format. I was able to decrypt it and then encrypt it using Symmetric keys and then updating the table column with the data. Now, there is a user sp which needs to encrypt the password for the new user and put it in the table. I'm not being able to make it work. I have this so far. Something somewhere is wrong. I dont know where. Please help Thanks. I used the same script to do the encryption initially but that was for the whole column. I need to see the encrypted version of the @inTargetPassword variable. But it's not working. It doesn't give me an error but gives me wrong data... declare @thePassword as varbinary(128) ,@inTargetPassword as varchar(255) ,@pwd3 as varchar(255) ,@theUserId bigint set @theUserId= 124564 set @inTargetPassword = 'test' OPEN SYMMETRIC KEY Key1 DECRYPTION BY CERTIFICATE sqlSecurity; Select @pwd3=EncryptByKey(Key_GUID('Key1') , @inTargetPassword, 1, HashBytes('SHA1', CONVERT( varbinary, [UserObjectId]))) from table1 where UserObjectId= @theUserId close symmetric key Key1
View Replies !
Slow Query....drop Index Works Fine!!!!!
We are running MS RS and SQL Server 2000 SP3. We have one LEDGER, where all the daily activities are stored. The LEDGER table has 4 indexes (1 clustered and 3 non-clustered). To get AR we use this table. Well problem is some times in 1-2 months, any simple AR query takes a long time and every other client gets slow response (queries are very slow or sometimes block). If we DROP any index on LEDGER table and again put it back (RECREATE), all our queries work fine and faster. This goes on till 1-2 months, till we see the same issue again. This is a classic case happened today. Queries were running fine till morning 8 AM. We upload some 50 thousand records to Ledger table (Data Conversion). Well after 30 mins, all simple AR queries started taking a long time. We DROPPED an index in LEDGER table and everything was faster....Just to be same we added back the same index again.......everything is Faster..... What is this. ....is it our QUERY, index or huge Transactions or no free space ??? We are scheduled to run SP4, next week. But is there any solution in the mean time on what is this? Also is they any way to KILL all SQL server processes that take more than a mins. We just don't want ALL our client to Slow down because of one query???? Thanks,
View Replies !
Report Works Fine Stand Alone, But Fails When Used As Subreport
I have a report which I have tested and works fine. now I'm trying to use it as a subreport. the "outer" or main report is very simple: it just has a company standard banner and some header/footer information, and then a single subreport. there is no passing of parameters between main report and sub report. the subreport does have its own parameter to govern its dataset, and provides its own default for that. The error that I'm getting is this: [rsErrorExecutingSubreport] An error occurred while executing the subreport €˜subreport1€™: An error has occurred during report processing. [rsMissingFieldInDataSet] The data set €˜WarrantMasterCube€™ contains a definition for the Field €˜Year€™. This field is missing from the returned result set from the data source. [rsErrorReadingDataSetField] The data set €˜WarrantMasterCube€™ contains a definition for the Field €˜Year€™. The data extension returned an error during reading the field. [rsMissingFieldInDataSet] The data set €˜WarrantMasterCube€™ contains a definition for the Field €˜Month€™. This field is missing from the returned result set from the data source. [rsErrorReadingDataSetField] The data set €˜WarrantMasterCube€™ contains a definition for the Field €˜Month€™. The data extension returned an error during reading the field. [rsMissingFieldInDataSet] The data set €˜WarrantMasterCube€™ contains a definition for the Field €˜Date€™. This field is missing from the returned result set from the data source. [rsErrorReadingDataSetField] The data set €˜WarrantMasterCube€™ contains a definition for the Field €˜Date€™. The data extension returned an error during reading the field. [rsMissingFieldInDataSet] The data set €˜WarrantMasterCube€™ contains a definition for the Field €˜Wt_TO_MTD€™. This field is missing from the returned result set from the data source. [rsErrorReadingDataSetField] The data set €˜WarrantMasterCube€™ contains a definition for the Field €˜Wt_TO_MTD€™. The data extension returned an error during reading the field. [rsNone] An error has occurred during report processing. Of course, this doesn't happen when I execute the subreport by itself. What kinds of things should I be looking at to get to the bottom of this. Thanks!
View Replies !
Multivalue Works Fine In The Sproc But Not In Bids Or Reportserver
Hi, I have a report which has multivalue parameters enabled and If i give NULL it displays everything correctly. But if I give different ClientId it doesnt do it in the report.. But if i run my sproc in VS2005 and in ssms it works the way i want it. this is my sproc Code Snippet set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go ALTER Procedure [dbo].[usp_GetOrdersByOrderDate] @StartDate datetime, @EndDate datetime, @ClientId nvarchar(max)= NULL AS Declare @SQLTEXT nvarchar(max) if @ClientId is NULL BEGIN SELECT o.OrderId, o.OrderDate, o.CreatedByUserId, c.LoginId, o.Quantity, o.RequiredDeliveryDate, cp.PlanId, cp.ClientPlanId --cp.ClientId FROM [Order] o Inner Join ClientPlan cp on o.PlanId = cp.PlanId -- and o.CreatedByUserId = cp.UserId Inner Join ClientUser c on o.CreatedByUserId = c.UserId WHERE --cp.ClientId = @ClientId --AND o.OrderDate BETWEEN @StartDate AND @EndDate ORDER BY o.OrderId DESC END ELSE BEGIN SELECT @SQLTEXT = 'Select o.OrderId, o.OrderDate, o.CreatedByUserId, c.LoginId, o.Quantity, o.RequiredDeliveryDate, cp.PlanId, cp.ClientPlanId --cp.ClientId FROM [Order] o Inner Join ClientPlan cp on o.PlanId = cp.PlanId --AND cp.ClientId in ('+ convert(Varchar, @ClientId) + ' ) Inner Join ClientUser c on o.CreatedByUserId = c.UserId WHERE cp.ClientId in (' + convert(Varchar,@ClientId) + ') AND o.OrderDate BETWEEN ''' + Convert(varchar, @StartDate) + ''' AND ''' + convert(varchar, @EndDate) + ''' ORDER BY o.OrderId DESC' exec(@SQLTEXT) END --return (@SQLTEXT) I have 2 datasets in this report one for the above sproc and other dataset that gives me the clientname and it is as follows Code Snippet ALTER Procedure [dbo].[usp_GetClientsAll] @ClientId nvarchar(max) = NULL AS --Declare @ClientId nvarchar(max) SELECT NULL ClientId, '<All Clients >' ClientName FROM Client Union SELECT ClientId, ClientName FROM Client Where ClientId = @ClientId OR ( ClientId = ClientId OR @ClientId IS NULL ) In the first dataset Parameter list i have omitted ClientId but kept it in the report parameter.. So when i give select all it works.. but when i just select particular it gives me the same result as Select all.. any help will be appreciated.. REgards Karen
View Replies !
Problems Publishing My Personal Website - Works Fine Locally!
People,I'm trying to publish my first website and am having a few problems.I've got Visual Web Developer 2005 Express and am trying to use the Personal Website Starter Kit. (my SQL server is SQL Server Express Edition 2005 - which is also running on my local machine)It seems to work fine when I run it on my localhost, as soon as I ftp it up to my web hosting company, I get an error message (see below) :-An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) My hypothesis is :-It would appear to me that when running locally, the starter kit website uses my installation of SQL 2005 Express Edition, but when I upload all the files, I'm guessing the application is still trying to point at a local instance of SQL on my local PC which it now cannot see. I'm guessing I need to somehow upload the SQL database onto my web host (I've purchased 100M of SQL Server 2005 space), and point the application at that SQL instance instead. But I don't know if I'm right about all this, or indeed how to do it if I am. Can anyone help?Much thanks in advance,Will
View Replies !
Long Running Query In SQL 2005 But Works Fine In SQL 2000
I have a simple update statement that is running forever in SQL 2005 but works fine in SQL 2000. We have a new server we put SQL 2005, restored db. The table in question WEEKLYSALESHISTORY I even re-indexed all the indexes and rebuilt the stats as well. But still no luck, still running extremely long. 1 hour 20 minutes. I'll try to give you some background on these table. Weeklysalehistory has approx 30 fields. I have 11 indesxes set up weekending date being one of them. And replication control has index on lasttrandatetime as well. So I think my indexes are fine. /* Update WeekEnding Date for current weeks WeeklySales Records */ Update WeeklySalesHistory set weekendingdate = (SELECT LastTransDateTime from ReplicationControl where TableName = 'WEEKHST') where weekendingdate is null Weekly sales has approx 100,000,000 rows Replication control has 631,000 (Ithink I can delete some from here to bring it down to 100 or 200 records) Although I don't think this is issue since on 2000 has same thing and works fine. I was trying to do this within SSIS and thought that was issue. I am new so SSIS but it runs long even if I just run it as a job with this simple Update statement so I think its something with tables, etc that is wrong. One thing on noticed if I look at the statistics in SQL Server Management studio there is a ton of stats. some being statistics on indexes which makes sense then I have a ton of hind_113_9_6 and simiiar one like this. I must have 90 or so named like this. Not sure how to check on SQL 2000 all the stats to see if they moved over from there or what. I checked a few other tables and don't have all these extra stats. Could this be causing the issue do I need to delete all these extras? Any help would be greatly appreciated. Stacy
View Replies !
Stored Procedure Works Fine, But Doesnt Preview? (Beginner)
I modified this stored procedure with the code highlighted, and now it runs forever on reporting services. Can anyone tell me what might be causing this? Here's my code. When i run it in Management studio and the dataset in reporting services, it works fine. But when it comes to previewing it, it runs forever. USE [RC_STAT] GO /****** Object: StoredProcedure [dbo].[PROC_RPT_EXPENSE_DETAIL_DRILLDOWN] Script Date: 06/29/2007 11:34:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[PROC_RPT_EXPENSE_DETAIL_DRILLDOWN] (@Region int = Null) AS BEGIN SELECT [Item_Ledger_Posting_Datetime] Post_Date ,'SMP' Budget_Type ,'Invoice' as Document_Type ,[Item_Ledger_Document_No] Document_Number ,[Item_Description]+' '+'('+[Item_No]+')' Entry_Description ,ISNULL(RC_STAT.dbo.udf_Correct_Price(Item_No, Item_Ledger_Posting_Datetime, 'SALESAMP') * -1*Item_Ledger_Invoiced_Qty,Item_Ledger_Cost_Posted_GL * -1 ) Amount ,-1*[Item_Ledger_Invoiced_Qty] Quantity ,Customer_Name ,'' External_Doc_no ,[Item_Ledger_Sales_Responsible] SR_Code ,[Item_Ledger_Mars_Period_Code] ThePeriod ,[Item_Ledger_Mars_Year] TheYear ,Territory.Name AS Territory_Name ,Region.Region AS Region_Name ,Budget_Reporting.Budget_Reporting_Group_ID ,Budget_Reporting_Group.Budget_Reporting_Group_Description FROM [NavisionReplication].[dbo].[Qry_Item_Ledger_Detail] INNER JOIN NavisionReplication.dbo.Tbl_Salesperson_Purchaser AS Salesperson_Purchaser ON [Item_Ledger_Sales_Responsible] = Salesperson_Purchaser.SalesPerson_Purchaser_Code INNER JOIN RC_DWDB_INSTANCE_1.dbo.Territory AS Territory ON Territory.Code = Salesperson_Purchaser.Territory_Code INNER JOIN RC_DWDB_INSTANCE_1.dbo.Tbl_Budget_Reporting As Budget_Reporting ON Budget_Reporting.Salesperson_Purchaser_Code = Salesperson_Purchaser.Salesperson_Purchaser_Code LEFT OUTER JOIN RC_DWDB_INSTANCE_1.dbo.Region AS Region ON Territory.Region_Key = Region.Region_Key INNER JOIN RC_DWDB_INSTANCE_1.dbo.Tbl_Budget_Reporting_Group As Budget_Reporting_Group ON Budget_Reporting_Group.Budget_reporting_Group_ID = Budget_Reporting.Budget_Reporting_Group_ID WHERE Region.Region_Key = @Region AND [Item_Ledger_Mars_Year] = 2007 AND [Item_Ledger_Amount]= 0 UNION ALL SELECT [GL_Entry_Posting_DateTime] ,Budget_Reporting.[Budget_Type_Code] ,[Document_Type] ,[GL_Entry_Document_No] ,[GL_Entry_Description] ,[GL_Entry_Amount] ,0 Quantity ,[User_ID] ,[GL_Entry_External_Document_No] ,[Sales_Responsible] ,[Mars_Period_Code] ,[Mars_Year] ,Territory.Name AS Territory_Name ,Region.Region AS Region_Name ,Budget_Reporting.Budget_Reporting_Group_ID ,Budget_Reporting_Group.Budget_Reporting_Group_Description FROM [NavisionReplication].[dbo].[Tbl_GL_entry] GL_entry INNER JOIN [RC_DWDB_INSTANCE_1].[dbo].[Tbl_Budget_Accounts] Budget_Accounts ON Budget_Accounts.[GL_Account_No] = GL_entry.[GL_Account] INNER JOIN NavisionReplication.dbo.Tbl_Salesperson_Purchaser AS Salesperson_Purchaser ON GL_entry.[Sales_Responsible] = Salesperson_Purchaser.SalesPerson_Purchaser_Code INNER JOIN RC_DWDB_INSTANCE_1.dbo.Territory AS Territory ON Territory.Code = Salesperson_Purchaser.Territory_Code LEFT OUTER JOIN RC_DWDB_INSTANCE_1.dbo.Region AS Region ON Territory.Region_Key = Region.Region_Key INNER JOIN RC_DWDB_INSTANCE_1.dbo.Tbl_Budget_Reporting As Budget_Reporting ON Budget_Reporting.Salesperson_Purchaser_Code = Salesperson_Purchaser.Salesperson_Purchaser_Code INNER JOIN RC_DWDB_INSTANCE_1.dbo.Tbl_Budget_Reporting_Group As Budget_Reporting_Group ON Budget_Reporting_Group.Budget_reporting_Group_ID = Budget_Reporting.Budget_Reporting_Group_ID WHERE GL_entry.[Mars_Year] = 2007 END
View Replies !
Permission Issue With Tempdb Works Fine In SQL2000 But Not SQL2005
the following SQL works fine in SQL2000 but gets a permissions error when run on SQL2005: IF not exists (SELECT * FROM tempdb.dbo.sysindexes WHERE NAME = 'PK_tblGuidContractMove') BEGIN IF @DEBUG = 1 PRINT 'airsp_CopyContracts.PK_tblGuidContractMove' EXECUTE('ALTER TABLE #tblGuidContractMove ALTER COLUMN guidSource GUID NOT NULL') EXECUTE('ALTER TABLE #tblGuidContractMove ALTER COLUMN guidDestination GUID NOT NULL') EXECUTE('ALTER TABLE #tblGuidContractMove ALTER COLUMN guidContractMove GUID NOT NULL') EXECUTE('ALTER TABLE #tblGuidContractMove WITH NOCHECK ADD CONSTRAINT [PK_tblGuidContractMove] PRIMARY KEY CLUSTERED ( [guidSource], [guidDestination], [guidContractMove] ) ON [PRIMARY]') END The user permissions are set the same in both 2000 and 2005 can you please explain what changed and what are the minimum permissions need for the user to be able to make these changes to the temporary table which the user created.
View Replies !
Update Table From MS2005 To Oracle 9.2 - No Solution Works For Me
Hi, I have been fighting this problem for several days now. All I need to do is run a query against a table on mssql 2005 server and update a table (only update) in Oracle Here are some of the things I have tried: 1) from a forum tip, I set up a dataflow: OLE DB Source (MS SQL) -> Derived Column -> OLE DB Command (Oracle) - I get "Error at Data Flow Task [OLE DB Command [2850]]: Columns "NyNamn" and "id" cannot convert between unicode and non-unicode string data types." 2) I have tried a Source - OLE DB Source (MS SQL) -> Derived Column -> OLEDB Desination (Oracles OLEDB) - Error when trying to preview: TITLE: Microsoft Visual Studio ------------------------------ Error at Data Flow Task [OLE DB Destination [2953]]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x8000FFFF. Error at Data Flow Task [OLE DB Destination [2953]]: Opening a rowset for ""APPINV2"."OWNERS"" failed. Check that the object exists in the database. ------------------------------ ADDITIONAL INFORMATION: Exception from HRESULT: 0xC02020E8 (Microsoft.SqlServer.DTSPipelineWrap) 3) I have tried a Source - OLE DB Source (MS SQL) -> Derived Column -> OLEDB Desination (MicrosoftsOLEDB for Oracle) - Error when trying to preview: TITLE: Microsoft Visual Studio ------------------------------ Error at Data Flow Task [OLE DB Destination [2953]]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005. An OLE DB record is available. Source: "Microsoft OLE DB Provider for Oracle" Hresult: 0x80004005 Description: "Unspecified error". An OLE DB record is available. Source: "Microsoft OLE DB Provider for Oracle" Hresult: 0x80004005 Description: "Oracle error occurred, but error message could not be retrieved from Oracle.". An OLE DB record is available. Source: "Microsoft OLE DB Provider for Oracle" Hresult: 0x80004005 Description: "Data type is not supported.". Error at Data Flow Task [OLE DB Destination [2953]]: Opening a rowset for ""APPINV2"."OWNERS"" failed. Check that the object exists in the database. ------------------------------ ADDITIONAL INFORMATION: Exception from HRESULT: 0xC02020E8 (Microsoft.SqlServer.DTSPipelineWrap) I have full rights on the oracle database with the account used, i can connect with toad with no problems. To me, this should be a simple task. has anyone got any advice for me ? Thanks
View Replies !
Inserting Multiple Records To A Table
Hi.. I really need a help. Is there any way to insert multiple records into a table in one go? I have a table named Fruit. It contains FruitId,OwnerId,Colour The list of colour is got from another table name FruitColour. FruitColour Consists of 2 column, FruitName and Colour. Is it possible to insert multiple records into Fruit table with one query if only the colour is changed. Sample case I have an Apple. Fruit id=2 OwnerId=2 Colour -- > Select Colour From FruitColour where FruitName='Apple' (Will return multiple records) I tried to insert using this query: Insert into Fruit(FruitId,OwnerId,Colour) Values (2,2,Select Colour from FruitColour where FruitName='Apple'). Gives me this error Subqueries are not allowed in this context. Only scalar expressions are allowed. I need to do this because actually I am inserting multiple fruit at one time, and each have multiple colour. If I need to insert the colour one by one for each fruit it will takes a very long time. Any suggestion are welcomed. Thank you in advanced.
View Replies !
Retrieving Records And Inserting Into Table
Folks: I need help with this. When I run the below script (only select) it retrives around 130K records and gives me the output within 2 mins. Whenever I try to put the same output in a temp or permanent table it takes hours. Any Idea why? SET NOCOUNT ON DECLARE @ImportId INT SET @ImportId = 5151 DECLARE @ResultXML XML SET @ResultXML = (SELECT ResultXML FROM tbRequests WITH(NOLOCK) WHERE ImportId = @ImportId) SELECT resultNode.value('(./DealName)[1]','VARCHAR(200)') AS DealName, resultNode.value('(./CUSIP)[1]','VARCHAR(100)') AS CUSIP, CASE WHEN resultNode.value('(./Vintage)[1]','VARCHAR(100)') = '' THEN NULL ELSE resultNode.value('(./Vintage)[1]','INT') END AS Vintage, resultNode.value('(./PoolPoolType)[1]','VARCHAR(100)') AS PoolType, CASE WHEN resultNode.value('(./PaidOff)[1]','VARCHAR(100)') = '' THEN NULL ELSE resultNode.value('(./PaidOff)[1]','BIT') END AS PaidOff FROM @ResultXml.nodes('./WebService1010DataOutput') resultXml(resultXmlNode) CROSS APPLY resultXmlNode.nodes('./Results/Result') resultNodes(resultNode) =================================================================================== Same Query when trying to insert the records in a temp table it takes hours. =================================================================================== SET NOCOUNT ON DECLARE @ImportId INT SET @ImportId = 5151 DECLARE @ResultXML XML SET @ResultXML = (SELECT ResultXML FROM tbRequests WITH(NOLOCK) WHERE ImportId = @ImportId) create table #TResults ([ID] [INT] IDENTITY(1,1) NOT NULL, DealName VARCHAR(200), CUSIP VARCHAR(100), Vintage INT, PoolType VARCHAR(100), PaidOff BIT) INSERT into #TResults (DealName,CUSIP,Vintage,PoolType,PaidOff) SELECT resultNode.value('(./DealName)[1]','VARCHAR(200)') AS DealName, resultNode.value('(./CUSIP)[1]','VARCHAR(100)') AS CUSIP, CASE WHEN resultNode.value('(./Vintage)[1]','VARCHAR(100)') = '' THEN NULL ELSE resultNode.value('(./Vintage)[1]','INT') END AS Vintage, resultNode.value('(./PoolPoolType)[1]','VARCHAR(100)') AS PoolType, CASE WHEN resultNode.value('(./PaidOff)[1]','VARCHAR(100)') = '' THEN NULL ELSE resultNode.value('(./PaidOff)[1]','BIT') END AS PaidOff FROM @ResultXml.nodes('./WebService1010DataOutput') resultXml(resultXmlNode) CROSS APPLY resultXmlNode.nodes('./Results/Result') resultNodes(resultNode) SELECT * FROM #TResults ============================================ Thanks !
View Replies !
Xp_sendmail: Failed With Mail Error 0x80040111 It Works Fine When You Do A Test From Enterprise Manager
Hello I am receiving the dreaded mail error listed above. I can send out a test E-mail from Enterprise Manager to operators, but I cannot run this Transact query: EXEC master.dbo.xp_sendmail @RECIPIENTS = araz***@***.com(removed email address), @SUBJECT = 'test' I receive: Server: Msg 18025, Level 16, State 1, Line 0 xp_sendmail: failed with mail error 0x80040111 I have stopped/restarted the SQL SERVER AGENT but haven't done much else as I haven't been able to. Should it work through transact SQL if the test email works from Enterprise Manager? This is SQL 2000 SP4 running on Win2K in the domain. Thank you.
View Replies !
Selecting Records From One Column In A Table And Inserting..
Godwin writes "Hello, Heres my question.. I have 2 tables.2 paticular columns exist in both the tables. I want to be able to select those 2 columns on the 1st table and insert them on to the same 2 columns on the 2nd table. Now,this 2nd table has another 3 columns that exist in another table.I would like to take those 3 column values from that 3rd table and insert it into the 2nd table by modifying those existing records in the 2nd table.In the 3rd table,there will be around 5 records...I want to copy the existing records 5 times in the 2nd table and insert the 3rd tables rows inside the 2nd table in that respective column for 5 rows. I hope you understand what I mean...Im sorry for really confusing.. Please help me Thanks Godwin"
View Replies !
RESTORE FILELIST Is Terminating Abnormally Error When Running A DTS Package In SQL 2005. Works Fine In SQL 2000
Currently I receive the following error when executing script within a DTS package in SQL 2005 (it seems to be working in SQL 2000): Processed 27008 pages for database 'Marketing', file 'Marketing_Data' on file 5. Processed 1 pages for database 'Marketing', file 'Marketing_Log' on file 5. BACKUP DATABASE successfully processed 27009 pages in 15.043 seconds (14.708 MB/sec). (5 row(s) affected) Msg 213, Level 16, State 7, Line 1 Insert Error: Column name or number of supplied values does not match table definition. Msg 3013, Level 16, State 1, Line 1 RESTORE FILELIST is terminating abnormally. The code I am using is: -- the original database (use 'SET @DB = NULL' to disable backup) DECLARE @DB varchar(200) SET @DB = 'Marketing' -- the backup filename DECLARE @BackupFile varchar(2000) SET @BackupFile = 'C:SQL2005 dbsMarketing.dat' -- the new database name DECLARE @TestDB2 varchar(200) SET @TestDB2 = datename(month, dateadd(month, -1, getdate())) + convert(varchar(20), year(getdate())) + 'Inst1' -- the new database files without .mdf/.ldf DECLARE @RestoreFile varchar(2000) SET @RestoreFile = 'C:SQL2005 dbs' + @TestDB2 DECLARE @RestoreLog varchar (2000) SET @RestoreLog = 'C:SQL2005 dbs' + @TestDB2 -- **************************************************************** -- no change below this line -- **************************************************************** DECLARE @query varchar(2000) DECLARE @DataFile varchar(2000) SET @DataFile = @RestoreFile + '.mdf' DECLARE @LogFile varchar(2000) SET @LogFile = @RestoreLog + '.ldf' IF @DB IS NOT NULL BEGIN SET @query = 'BACKUP DATABASE ' + @DB + ' TO DISK = ' + QUOTENAME(@BackupFile, '''') EXEC (@query) END -- RESTORE FILELISTONLY FROM DISK = 'C: empackup.dat' -- RESTORE HEADERONLY FROM DISK = 'C: empackup.dat' -- RESTORE LABELONLY FROM DISK = 'C: empackup.dat' -- RESTORE VERIFYONLY FROM DISK = 'C: empackup.dat' IF EXISTS(SELECT * FROM sysdatabases WHERE name = @TestDB2) BEGIN SET @query = 'DROP DATABASE ' + @TestDB2 EXEC (@query) END RESTORE HEADERONLY FROM DISK = @BackupFile DECLARE @File int SET @File = @@ROWCOUNT DECLARE @Data varchar(500) DECLARE @Log varchar(500) SET @query = 'RESTORE FILELISTONLY FROM DISK = ' + QUOTENAME(@BackupFile , '''') CREATE TABLE #restoretemp ( LogicalName varchar(500), PhysicalName varchar(500), type varchar(10), FilegroupName varchar(200), size int, maxsize bigint ) INSERT #restoretemp EXEC (@query) SELECT @Data = LogicalName FROM #restoretemp WHERE type = 'D' SELECT @Log = LogicalName FROM #restoretemp WHERE type = 'L' PRINT @Data PRINT @Log TRUNCATE TABLE #restoretemp DROP TABLE #restoretemp IF @File > 0 BEGIN SET @query = 'RESTORE DATABASE ' + @TestDB2 + ' FROM DISK = ' + QUOTENAME(@BackupFile, '''') + ' WITH MOVE ' + QUOTENAME(@Data, '''') + ' TO ' + QUOTENAME(@DataFile, '''') + ', MOVE ' + QUOTENAME(@Log, '''') + ' TO ' + QUOTENAME(@LogFile, '''') + ', FILE = ' + CONVERT(varchar, @File) EXEC (@query) END
View Replies !
Trouble With Adventure Works
Hey All, I'm new to the whole DB thing so I wanted to start off easy and download SQL Express. That part worked fine so I tried to install the Adventure Works DB to get some practice using the SQL commands. The problem is every time I click on a table in Adventure Works and choose Open Table I get a Microsoft SQL Server Management Studio box that pops up. The error says: Class Not Registered (Exception from HRESULT: 0x80040154 REGDB_E_CLASSNOTREG)) (Microsoft.SqlServer.SqlTools.VSIntegration) Help!! Any ideas out there how to get the Adventure Works DB working? Thx much.
View Replies !
Update Table Lastrow Before Inserting
HI ALL, I have one table. Table1 --------------- ID int BEGDATE datetime ENDDATE datetime I want update (last-1) row ENDDATE column value, after insert new row and set ENDDATE = inserted.Begdate - 1 I want set table following sturucture select * from Table1 ID BEGDATE ENDDATE --------------------------------------------- 1 01/01/2008 02/01/2008 2 02/02/2008 03/19/2008 3 03/20/2008 Wich way you are offer? Regards, MAHIR M. QULUZADE
View Replies !
SQL SERVER ACCESS DENIED!! BUT Everything Works On MSDE And Works SHOWING RECORDS ON SQL SERVER!! PLEASE HELP
I've got a popular problem so i get a message that server acces denied! .. But that what is different in my error.... When i use same setting same database and connection string (on MSDE server) there is no problem... On SQL server i have got windwos authentication but i added all accounts as ASPNET and SA.... and when i try to connect by RETTO - name of my server server=RETTO;uid=sa;pwd=password;database=db1; or by Integrated Security=SSPIserver=RETTO;uid=RETTOASPNET;database=db1; I CAN BROWSE RECORDS THERE ARE NO PROBLEMS WITH CONNECTION!!! but when i try to update or iinsert or delete something in database there becomame this error that access denied or server does not exist!!! PLEASE HELP I'm FIGHTING WITH THAT FOR OVER 5 DAYS!!! I MADE FOR MY ACCOUNTS (SA, ASPNET) ALL THINGS ALLOWED AS EXECUTING stored procedures.. OR ACCESING datatables with insert delete and update query WHERE IS THE PROBLEM!!!??
View Replies !
How To Fine A Hole In A Records?
Hi all!I need your help to realize algorithm for stored proc or trigger.tool: MS SQL server 2000, T-SQLTABLE:[unique_id] [mynumber] [week][unique_id] - bigint,primary key, identity auto-increnment[week] - int, 1-53, week number[mynumber] - int, 1 - 7, for every week, daily record one per day, upto 7 per weekso, for every week we have a mynumber from 1 to 7or nothing (if no records for that day),we can insert or delete mynubers in any order, at willEXAMPLE:week 1, mynumber 1,2,3 - so if we insert a new record, mynumber value= 4week 2, mynumber 1,2,3,5,7 - so next mynumber = 4QUESTION:How to use _only_ T-SQL find a missed numbers for particular week whenI'm insert a records?Thanks.Chapai
View Replies !
OR Works Fine, When I Add AND Things Go Wrong (was &"Help With Simple Query&")
Hi I really need some help I have been banging my head against a brick wall for the last day or so... I need some assistance with a query. Maybe what I am trying to do is not possible but I am sure it is. I have a ASP page with a SQL 2005 Express backend. I would like to query a table based on a dropdownlist and checkboxes on my form. The perameter in the drop down list is a service so I am querying records based on a service. The checkboxes are locations such as north,east, south and west. So I am building OR statements with these. For example I am looking for plumbers in the north and east. The OR part works fine. Its when I add the service into the query things go wrong. Here is my tables Company --------- PK CompanyID ComapnyName Service -------- PK ServiceID FK CompanyID ServiceName Region -------- PK RegionID FK CompanyID North East South West The below works fine when querying companies in different locations: SELECT TblCompany.CompanyID, TblCompany.CompanyName, TblRegion.North, TblRegion.East, TblRegion.South, TblRegion.West FROM TblCompany INNER JOIN TblRegion ON TblCompany.CompanyID = TblRegion.CompanyID WHERE (TblRegion.Scotland = @Pram1) OR (TblRegion.Wales = @Pram2) OR (TblRegion.NorthEast = @Pram3) OR (TblRegion.NorthWest = @Pram4) Now the problem is when I add in the service table. Sometimes I get all records returned. So even if I query a plumber in the south and east I get records for companies that dont even have a particular service in the perameter. I can provide more info if need - I am guessing my design is all wrong. The way I see this happening from a GUI is a dropdown being the service WHERE perameter and the truefalse BIT tick boxes being the OR perameters - any help would be great - many thanks in advance.
View Replies !
Sql Report Works Fine On Internal Servers - Hosed On External Servers - Need Some Help
I have a report that was designed using SQL Reporting Services that sits on a SQL reporting server. It's nothing too exciting, it is essentially a three page application with legal jumbo on pages 2 and 3 and applicant data in fields on page 1. We use rectangles to force page breaks to page 2 and to page 3. When running the report on the report server, it shows and prints fine. When running the report from the QA website internally, it shows and prints just fine. When running the report from the production website from a machine internally, it shows and prints just fine. When running the report from outside of the company network, the report is jacked. It obliterates large chunks of text, crams text together, and creates blank pages. I need help in determining where I even begin with trouble shooting this!
View Replies !
SQL Server VARCHAR(MAX) Column Returns Error While Inserting Records Into Table(ODBC Driver: SQL Native Client)
I created very simple table with 3 columns and one is varchar(max) datatype When i insert records thru VC++ ADO code i am getting this error Exception Description Multiple-step OLE DB operation generated errors. Check e ach OLE DB status value, if available. No work was done. and Error Number:: -2147217887 ODBC Driver: SQL Native Client SQL server 2005 Table CREATE TABLE [dbo].[RAVI_TEMP]( [ID] [int] NULL, [Name] [varchar](max) NULL, [CITY] [varchar](50) NULL ) VC++ code #include "stdafx.h" #include <string> #include <strstream> #include <iomanip> int main(int argc, char* argv[]) { try { HRESULT hr = CoInitialize(NULL); _RecordsetPtr pExtRst = NULL; _bstr_t bstrtDSN, bstrtSQL; bstrtDSN = L"DSN=espinfo;UID=opsuser;PWD=opsuser;"; bstrtSQL = L"SELECT * FROM RAVI_TEMP"; _variant_t vartValueID,vartValueNAME,vartValueCITY; _bstr_t bstrtValueID,bstrtValueNAME,bstrtValueCITY; pExtRst.CreateInstance(__uuidof(Recordset)); hr = pExtRst->Open(bstrtSQL, bstrtDSN, adOpenDynamic, adLockOptimistic, adCmdText); hr = pExtRst->AddNew(); bstrtValueID = L"1"; vartValueID = bstrtValueID.copy(); bstrtValueNAME = L"RAVIBABUBANDARU"; vartValueNAME = bstrtValueNAME.copy(); bstrtValueCITY = L"Santa Clara"; vartValueCITY = bstrtValueCITY.copy(); pExtRst->GetFields()->GetItem(L"ID")->Value = vartValueID; pExtRst->GetFields()->GetItem(L"NAME")->Value = vartValueNAME; pExtRst->GetFields()->GetItem(L"CITY")->Value = vartValueCITY; pExtRst->Update(); pExtRst->Close(); } catch(_com_error e) { printf("Exception Description %s and Error Number:: %d",(LPTSTR)e.Description(),e.Error()); return e.Error(); } return 0; CoUninitialize(); } if i use regular SQL ODBC driver, no error but its truncating the data Adv Thanks for your help
View Replies !
Update Table From Old Records
I'm using SQL Server 2000. I have a table with data similar to this.... Multi field = 0 indicates current record, 1 indicates an old record FWK NVQ Multi Key Start Date NVQ Date FWK Date NULL NULL 0 123456 03/04/2006 NULL NULL NULL NULL 1 123456 03/04/2005 01/09/2006 NULL NULL NULL 0 234567 03/04/2006 NULL NULL NULL NULL 1 234567 03/06/2005 04/10/2005 03/11/2005 NULL NULL 0 345678 03/04/2004 NULL NULL NULL NULL 1 345678 03/07/2003 NULL 01/12/2003 NULL NULL 1 345678 03/08/2002 NULL NULL NULL NULL 0 456789 30/09/2002 11/06/2003 NULL NULL NULL 1 456789 29/08/2000 NULL NULL NULL NULL 0 567890 30/09/2002 11/06/2003 11/06/2003 NULL NULL 1 567890 29/08/2000 30/05/2001 NULL NULL NULL 0 678901 03/04/2006 01/09/2006 15/09/2006 NULL NULL 1 678901 30/03/2005 30/08/2005 15/08/2005 NULL NULL 0 789012 02/03/2000 03/09/2000 15/09/2000 NULL NULL 0 789013 30/06/2001 07/08/2001 14/08/2001 I need to update the table, setting the first two columns to the date of the old records... ie. I want the table to look like this... FWK NVQ Multi Key Start Date NVQ Date FWK Date NULL 01/09/2006 0 123456 03/04/2006 NULL NULL NULL NULL 1 123456 03/04/2005 01/09/2006 NULL 03/11/2005 04/10/2005 0 234567 03/04/2006 NULL NULL NULL NULL 1 234567 03/06/2005 04/10/2005 03/11/2005 01/12/2003 NULL 0 345678 03/04/2004 NULL NULL NULL NULL 1 345678 03/07/2003 NULL 01/12/2003 NULL NULL 1 345678 03/08/2002 NULL NULL NULL NULL 0 456789 30/09/2002 11/06/2003 NULL NULL NULL 1 456789 29/08/2000 NULL NULL NULL 30/05/2001 0 567890 30/09/2002 11/06/2003 11/06/2003 NULL NULL 1 567890 29/08/2000 30/05/2001 NULL 15/08/2005 30/08/2005 0 678901 03/04/2006 01/09/2006 15/09/2006 NULL NULL 1 678901 30/03/2005 30/08/2005 15/08/2005 NULL NULL 0 789012 02/03/2000 03/09/2000 15/09/2000 NULL NULL 0 789013 30/06/2001 07/08/2001 14/08/2001 Can anyone help me with this? Jon Code Snippet DECLARE @TABLE_JR TABLE ([FWK] datetime, [NVQ] datetime, [Multi] Smallint, [Key] varchar(10), [Start Date] datetime, [NVQ Date] datetime, [FWK Date] datetime) INSERT INTO @TABLE_JR VALUES (null,null,0,'123456','2006-04-03',null,null) INSERT INTO @TABLE_JR VALUES (null,null,1,'123456','2005-04-03','2006-09-01',null) INSERT INTO @TABLE_JR VALUES (null,null,0,'234567','2006-04-03',null,null) INSERT INTO @TABLE_JR VALUES (null,null,1,'234567','2005-06-03','2005-10-04','2005-11-03') INSERT INTO @TABLE_JR VALUES (null,null,0,'345678','2004-04-03',null,null ) INSERT INTO @TABLE_JR VALUES (null,null,1,'345678','2003-07-03',null,'2003-12-01' ) INSERT INTO @TABLE_JR VALUES (null,null,1,'345678','2002-08-03',null,null ) INSERT INTO @TABLE_JR VALUES (null,null,0,'456789','2002-09-30','2003-06-11',null) INSERT INTO @TABLE_JR VALUES (null,null,1,'456789','2000-08-29',null,null) INSERT INTO @TABLE_JR VALUES (null,null,0,'567890','2002-09-30','2003-06-11','2003-06-11') INSERT INTO @TABLE_JR VALUES (null,null,1,'567890','2000-08-29','2001-05-30',null) INSERT INTO @TABLE_JR VALUES (null,null,0,'678901','2006-04-03','2006-09-01','2006-09-15') INSERT INTO @TABLE_JR VALUES (null,null,1,'678901','2005-03-30','2005-08-30','2005-08-15') INSERT INTO @TABLE_JR VALUES (null,null,0,'789012','2000-03-02','2000-09-03','2000-09-15') INSERT INTO @TABLE_JR VALUES (null,null,0,'789013','2001-06-30','2001-08-07','2001-08-14')
View Replies !
Update All The Records Of A Table On A Condition
Hi I have a two tables as follows Table Category { ID PK, LastUpdate DateTime } Table Master { ID PK Catrgory DateTime } I wanted to update Catrgory coulmn of all records in the Master table with the Value of LastUpdate of the CategoryTable the where the ID of the both the table are same Can any one please let me know the query ~Mohan
View Replies !
Trouble Inserting Values From Radiobuttons
Hi all, I am having issue with a set of radiobuttons. I have four radiobuttons associated by a groupname (answer). I am attempting to store the text of the selected radiobutton when the user make a selection and clicks submit. For reasons unknown... each of the radiobutton.checked values are remaining false hence I cannot interrogate for a checked equal true to insert associated text of check response. Here is how I am interrogating who is checked: If rb1.Checked = True Then useranswer = rb1.Text.ToString ElseIf rb2.Checked = True Then useranswer = rb2.Text.ToString ElseIf rb3.Checked = True Then useranswer = rb3.Text.ToString ElseIf rb4.Checked = True Then useranswer = rb4.Text.ToString End If I then attempt to insert this text to sql but none of the rb values are true hence a null wont insert. Cmd1.Parameters.Add(New SqlParameter("@answer", useranswer)) How can I evaluate grouped radiobutton checked values? Many thanks in advance... Scott
View Replies !
Unable To Update Or Delete SQL Table Records
Hello, I have been serching for weeks to resolve this problem. I am new to ASP.NET and trying to make the migration from ASP which I have programmed in for years. I am using Microsoft Visual Web Developer 2005 Express Edition and SQL Express Edtion. I have been working through the Microsoft Video Training at http://msdn.microsoft.com/vstudio/express/beginner/learningpath/ and created a web site using Tier 3 Lesson 8 as the model. My new web site which is a simple phone book applicaiton lets me read the table and select the record without any problem. But the update form lets me edit but when I attempt to Apply the update I get the following error. Server Error in '/Phonebook' Application. ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'Update' that has parameters: FirstName, LastName, PhoneNumber, BossGroup, Department, BossPickup, ShowInPhonebook, Type, Original_FirstName, Original_LastName, Original_PhoneNumber, Original_BossGroup, Original_Department, Original_BossPickup, Original_ShowInPhoneBook, Original_Type, Original_ItemID. Description: An unhundled expception occured during the execution of the current web request. Please review the stack trace for more information about the error and where it originiated in the code. The Stack Trace basiclly showes the same error as above. Also, when I attempt to delete the record I do not get an error but the record does not delete. What is interesting is that I can add a record so I do not believe that it is a security permissions issue. I have the ISS Authinication Method Enable Anonymous Access set on with full control. If anyone has any insight as to why this is occuring please let me know.
View Replies !
Trouble With Update Trigger Modifying Table Which Fired Trigger
Are there any limitations or gotchas to updating the same table whichfired a trigger from within the trigger?Some example code below. Hmmm.... This example seems to be workingfine so it must be something with my specific schema/code. We'reworking on running a SQL trace but if anybody has any input, fireaway.Thanks!create table x(Id int,Account varchar(25),Info int)GOinsert into x values ( 1, 'Smith', 15);insert into x values ( 2, 'SmithX', 25);/* Update trigger tu_x for table x */create trigger tu_xon xfor updateasbegindeclare @TriggerRowCount intset @TriggerRowCount = @@ROWCOUNTif ( @TriggerRowCount = 0 )returnif ( @TriggerRowCount > 1 )beginraiserror( 'tu_x: @@ROWCOUNT[%d] Trigger does not handle @@ROWCOUNT[color=blue]> 1 !', 17, 127, @TriggerRowCount) with seterror, nowait[/color]returnendupdate xsetAccount = left( i.Account, 24) + 'X',Info = i.Infofrom deleted, inserted iwhere x.Account = left( deleted.Account, 24) + 'X'endupdate x set Account = 'Blair', Info = 999 where Account = 'Smith'
View Replies !
SQL Update One Table With Records In Another Table
I am trying to update all recors in one table with records from another table. My script is only updating one record. How do I fix this? This is what I have: Code: set rec1=con.execute ("SELECT * FROM Cancels ORDER BY Canceldate ASC") rec2 = "update FC2003copy SET LPCancelDate = '" & rec1("canceldate") & "'" & _ "where CaseNum= '" & rec1("CaseNum") & "'" Con.Execute(rec2)
View Replies !
MS Access Back-end Works Fine, But SQL Server Back End NOT Working For Access Project
Hi I have 2 forms, each associated with its own table - they are linked together only by the fact that they share a common field, CustomerID.... I create a form (for table 1, called Customers) that brings up another form (for table 2, called Projects) based on the CustomerId that is selected in the first form from the Customers table - with a SQL back end it brings up ALL records in the second form (for the second table) with any CustomerIDs that exist in both tables - I set the link criteria [forms]![Customers]![CustomerID] and with an MS access back-end it works fine, but with a SQL back end it still returns ALL records with any ID that matches....not just the one I selected in the Customers form..... why?? thanks for reading this and for your help...
View Replies !
Insert / Update In Master Table And Also Save A History Of Changed Records : Using Data Flow/simple Sql Queries
Hi, My scenario: I have a master securities table which has 7 fields. As a part of the daily process I am uploading flat files into database tables. The flat files contains the master(static) security data as well as the analytics(transaction) data. I need to 1) separate the master (static) data from the flat files, 2) check whether that data is present in the master table, if not then insert that data into the master table 3) If data present then move that existing record to an history table and then update the main master table. All the 7 fields need to be checked to uniquely identify a single record in the master table. How can this be done? Whether we can us a combination of data flow items or write a sql procedure to do all this. Thanks in advance for your help. Regards, $wapnil
View Replies !
Select Records Between Dates - Query Works In VS 2005 But It Doesn't In Asp 3
Hello. I'm having troubles with a query that (should) return all therecords between two dates. The date field is a datetime type. The db isSQL Server 2000. When I try thisSELECT RESERVES.RES_ID, PAYMENTS_RECEIVED.PYR_ID,PAYMENTS_RECEIVED.PYR_VALUE, PAYMENTS_RECEIVED.PYR_DATE,CUSTOMERS.CUS_NAMEFROM RESERVES LEFT OUTER JOINPAYMENTS_RECEIVED ON RESERVES.RES_ID =PAYMENTS_RECEIVED.RES_ID LEFT OUTER JOINCUSTOMERS ON RESERVES.CUS_ID = CUSTOMERS.CUS_IDWHERE (PAYMENTS_RECEIVED.PYR_DATE >= '2006-03-20 00:00:00') AND(PAYMENTS_RECEIVED.PYR_DATE < '2006-03-27 00:00:00')on a "query builder" in visual studio, I get the results that I want.But when I use exactly the same query on an asp 3 vbscript script, Iget no results (an empty selection).I've done everything imaginable. I wrote the date as iso, ansi, britishformat using convert(,103) (that's how users will enter the dates),i've used cast('20060327' as datetime), etc. But I can't still get itto work. Other querys from the asp pages work ok. Any ideas?thanks a lot in advance
View Replies !
Inserting Data Into Two Tables (Getting ID From Table 1 And Inserting Into Table 2)
I am trying to insert data into two different tables. I will insert into Table 2 based on an id I get from the Select Statement from Table1. Insert Table1(Title,Description,Link,Whatever)Values(@title,@description,@link,@Whatever)Select WhateverID from Table1 Where Description = @DescriptionInsert into Table2(CategoryID,WhateverID)Values(@CategoryID,@WhateverID) This statement is not working. What should I do? Should I use a stored procedure?? I am writing in C#. Can someone please help!!
View Replies !
I Want To Transfer ONLY New Records AND Update Any Modified Records From Oracle Into SQL Server Using DTS
I need a little help here..I want to transfer ONLY new records AND update any modified recordsfrom Oracle into SQL Server using DTS. How should I go about it?a) how do I use global variable to get max date.Where and what DTS task should I use to complete the job? Data DrivenQuery? Transform data task? How ? can u give me samples. Perhaps youcan email me the Demo Package as well.b) so far, what I did was,- I have datemodified field in my Oracle table so that I can comparewith datelastrun of my DTS package to get new records- records in Oracle having datemodified >Max(datelastrun), and transferto SQL Server table.Now, I am stuck as to where should I proceed - how can I transfer theserecords?Hope u can give me some lights. Thank you in advance.
View Replies !
Update Statement Works Ok But No Result
here is my update statement in a stored procedure: create proc proc_add_comp @comp_answer nvarchar(300), @admin nvarchar(100), @comp_id int as update tbComp set comp_answer = comp_answer + ' - ' + @admin + ', ' + @comp_answer where comp_id=@comp_id then I try it like this : exec proc_add_comp 'new answer','by me',1 result is : (1 row(s) affected) but when I look in the db, nothing was changed, comp_answer still has its old value.. comp_answer is nvarchar type column..isnt add operation allowed in update statement? thanks...
View Replies !
Dateadd Update Works But Adds 2 Or 3 Yrs-not 1
I have a page that is supposed to add a year to a record when it loads. The problem is that it adds 2 or three years instead. Here is the page_load event:Sub page_load(sender as object, e as eventargs) Try Dim connection As SqlConnection = new SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim command As SqlCommand = new SqlCommand("Updateexpiredate", connection) command.CommandType = CommandType.StoredProcedure Dim param0 As SqlParameter = new SqlParameter("@memberid",SqlDbType.Int) param0.Direction = ParameterDirection.Input param0.Value = memberid command.Parameters.Add(param0) connection.Open() command.ExecuteNonQuery() connection.Close() myerror.Text = "Thank You! Your account was updated" Catch ex As Exception myerror.Text = ex.Message End Try End SubAnd here is the SPROC:CREATE PROCEDURE Updateexpiredate ( @memberid int ) AS UPDATE members SET expiredate=(dateadd(year,1,expiredate)) <--I also tried expiredate=(dateadd(month,12,expiredate)) with the same results WHERE memberID = @memberID GO
View Replies !
SELECT Works But UPDATE Fails. ?
This statement failsupdate ded_temp aset a.balance = (select sum(b.ln_amt)from ded_temp bwhere a.cust_no = b.cust_noand a.ded_type_cd = b.ded_type_cdand a.chk_no = b.chk_nogroup by cust_no, ded_type_cd, chk_no)With this error:Server: Msg 170, Level 15, State 1, Line 1Line 1: Incorrect syntax near 'a'.But this statement:select * from ded_temp awhere a.balance = (select sum(b.ln_amt)from ded_temp bwhere a.cust_no = b.cust_noand a.ded_type_cd = b.ded_type_cdand a.chk_no = b.chk_nogroup by cust_no, ded_type_cd, chk_no)Runs without error:Why? and How should I change the first statement to run my update. Thisstatement of course works fine in Oracle. :)tksken.
View Replies !
One Table Is Ultra Slow At Being Copied, Others Are Fine
This is a really really odd problem. Here's the situation. I've got a DB with several tables. Let's pick out two of those tables from the bunch.. they both have approx 2500 rows in them. I take one and duplicate it (right click, All Tasks->Export Data, copy tables, etc) and it duplicates just fine into another DB. Now, the second table.. takes FOREVER. Yet it has the same amount of rows in it! And this is a flat table export.. I'm not including dependent objects or anything like that. Not to mention this is slow, but when I use Red-Gate SQL Data Compare, it gets stuck when it hits this specific table. Anyone have any idea what would cause this?
View Replies !
|