Datetime-Based Operations

Apr 26, 2007

I'm new to SQL Server and relatively new to database design and I have a specific problem I'm trying to resolve.  I have a collection of records in a table (let's call them 'tasks') which represent some list of things that needs to be completed.  Each task has an associated datetime on which this action is to commence, and my applications is responsible for executing these tasks.  My first instinct is to regularly poll the 'tasks' table to determine if there are any tasks which have not been processed and are past their schedule start datetime.   But, I'm wondering if there is some sort of database feature that would  recognize that a task's starttime has arrived, and could somehow communicate this to my application without my application having to constantly poll the database.  Thanks.

View 5 Replies


ADVERTISEMENT

Status On Set Based Operations?

Aug 26, 2004

Every time I mention cursors, I hear a lot of people pointing out how you shouldn't use cursors and how set based operations are much faster.

However, procedural code offers the big advantage that I can embed status/progress type commands into a cursor loop and get accurate data on progress and ETA.

If I execute a single huge UPDATE/INSERT, I am at the whim and mercy of SQL Server. Seemingly simple statements often run for 50 hours+ and I have no clue how far along it is or anything remotely close to an ETA. Often, that is absolutely inacceptable to have mission criticial hardware to be churning through a process for DAYS without the slightest idea if it is actually making progress or not.

Is there any way to get progress/status on such an UPDATE/INSERT command?

View 11 Replies View Related

Make Math Operations With DateTime

Sep 23, 2007

hi,
how can i make mathematical operations with the DateTime format from thw Sql? -- this is the format 9/6/2007 11:09:00 PM --
how can i substract 30 days from that date and know the resulting one?
if i have two dates, how can i know what number of hours and minutes are between them (if they are fewer than 24), or what number of days and hours and minutes are (if the difference is grater than 24 hours)
please help me, thanks

View 2 Replies View Related

Questions About Bulk Copy Insert Using 'Memory Based Bulk Copy Operations'

Feb 1, 2007

Hi~,

Before implementing memory based bulk copy insert with IRowsetFastLoad interface of SQL Server 2005 OLE DB provider, I want to know some considerations.

- performance : compared with T-SQL's "BULK INSERT ..." and bcp utility

- SQL Server's resource usage : when running memory based bulk copy, server resource's influence

- server side action(behavior) : when server is busy, delayed-update means IRowsetFastLoad::Commit(true) method can insert right after?

- row-count : The rowcount limitation can be inserted by IRowsetFastLoad::InsertRow() method before IRowsetFastLoad::Commit

- any other guide lines

View 1 Replies View Related

Select Query Based On Datetime

Feb 12, 2002

I need to select certain rows based on a "datetime" column. I need to select rows from 8am yesterday until 8am today.
In Oracle I would use:
select * from foo where TIMESTAMP >= trunc(sysdate - 1) + 8/24 AND TIMESTAMP < trunc(sysdate) + 8/24.
This would start at 8am yesterday and end at 7:59am today.

How would I do this with T-SQL?

thank you,

Mark
Fiesta_donald@email.com

View 1 Replies View Related

Slipt Rows Based On Datetime

May 24, 2006

Hello!

I have a table that, among other columns, has two datetime columns which indicate the initial and the final time. This would be an exemple of data in this table:

row1:

initial_time: 2006-05-24 8:00:00

final_time: 2006-05-24 8:30:00

row2:

initial_time: 2006-05-24 8:35:00

final_time: 2006-05-24 9:15:00

I would like to split a row in two new rows if final time's hour is different of initial time's hour, so I would like to split row2 into:

row2_a:

initial_time: 2006-05-24 8:35:00

initial_time: 2006-05-24 8:59:59

row2_b:

initial_time: 2006-05-24 9:00:00

initial_time: 2006-05-24 9:15:00

Is it possible to do it in a query, I mean, without using procedures?

Thank you!

View 3 Replies View Related

Problem Updating A Record Based On A Datetime.

Sep 24, 2007

Hi People,
hope someone can help me out here with a little problem.
 Basically i've go a asp.net page which has a listbox on. This list box is populated from a SQL database table with the datetime of the a selected field. Thus in the list box you get a list of strings looking like this "24/09/07 12:58"
Also on the page is a submit button, and some other editing textboxes. The main issue here is the when the submit button is used i get the currently selected listbox timedate string and then pass this along with other items to update a record in the database based on the datetime in the listbox control.
 
Below is how i get the string from the listbox control
Dim except_time As DateTime
except_time = DropDownList1.SelectedValue
The expect_time is then passed to store procedure along with some other vars, which looks like this 
-- =============================================-- Author: Lee Trueman-- Create date: 1st Sept 2007-- =============================================CREATE PROCEDURE [dbo].[spExcept_UpdateData]  -- Add the parameters for the stored procedure here @validated bit, @update_time datetime, @except_time datetimeASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON
     -- Insert statements for procedure here UPDATE exceptions SET    validated = @validated,    update_time = @update_time WHERE  (except_time = @except_time)END
So validated and update_time should be updated when except_time is equal to @except_time
 
My problem is that the database never updates. If i debug the asp.net page the watch var shows the datetime in US format (I.e "09/24/07 12:58"), if this is true then this would explain why when it is passed to the stored proc nothing gets updated, as there would not be a date match.
can anyone see any silly mistakes i'm doing here ???? 

View 2 Replies View Related

Query Data Based On Moving Datetime.

Feb 5, 2008

I'm trying to query data from a database for a report that looks for the last 2 weeks starting at 10pm, taking a value once every 24 hours. Using

AND DateTime >= DateAdd(wk,-2,GETDATE())

AND DateTime <= GetDate()")
I easily get the last two weeks but the query obviously only grabs the data at the time the query runs. I need to be able to run it any time of the day but only grab the data at 10pm. I'm very new at this so please excuse my ignorance but I could really use some help with this. Thanks very much.

View 4 Replies View Related

SQL DateTime Limit = Enemy Of Historical Based Websites

Jun 18, 2007

I'm trying to create a website based on interesting historical facts, Searchable by date. I need each fact entry to have a datetime field in the database, but unfortunately this method only lets me go as far back as the year 1753 (for an inexplicable reason, I can go up to the year 9999).Is there something I'm overlooking here, or did Microsoft goof this one? Will I have to store my dates as 3 separate custom month/day/year fields? If anybody has a solution for this, please let me know (a B.C./A.D enabled solution isn't at all needed, but I'm open to that too).

View 1 Replies View Related

SELECT From DateTime Field Based On Current Date

Feb 5, 2008

I am trying to match records that are >= the current date. I have tried using:
SELECT DISTINCT name
FROM table
WHERE datefield >= DATEPART(month, GETDATE()) AND datefield >= DATEPART(day, GETDATE()) AND datefield >= DATEPART(year, GETDATE())
ORDER BY name
but this is not giving me the result that I am looking for. What is the best way to match a DateTime field type using the current date without the time?

View 5 Replies View Related

How To Convert UTC Based Datetime Values To Local Setting?

Sep 11, 2007

Hello:

I've recently discovered the MS CRM 3.0 stamps any datetime field in SQL as UTC (aka GMT). Even though the end user may select 12:00 noon on the CRM gui interface, the datetime is stamped in SQL as 16:00 (I'm in EST).

So, is there an easy way to read the 16:00 back to local EST, taking into account daylightsavings (DST)? Apparently in VB or C# this conversion is a trivial matter of using ToLocalTime(), but I don't believe SQL 2005 has such a convenient function.

I'm currently building a SQL view that I wish to use to support multiple reports, and it would be ideal for the view to translate the UTC datetime fields (even if via a user-defined function) to EST rather than coding every report or custom app to translate the UTC.

Any suggestions or links to code will be greatly appreciated!

Thanks,
Pete

View 5 Replies View Related

Insert Adjusted Datetime Into Sql Field Based On User Locale

Jul 29, 2004

Is there a way to adjust a date and time depending on the users locale before inserting into the database?

Users login in and their country of residence is stored in the database on signup. My server is in the US and I want to reset part of the users db record when it's the end of the day in their country so I need to enter the date and time into the db plus or minus the time difference, is there a function written to do this already or would i need to write my own?

View 1 Replies View Related

X-Axis Scalar Mode Based On DateTime Field - Not Working

Mar 8, 2007

I have a chart showing quantity against time. I had been using X-Axis in category mode, but wanted to include all dates, so changed it to Scalar mode by checking "Numeric or time-scale values".

However instead of displaying dates it simply shows integers, and to make things worse, Y-axis values have all come out as zero. It appears that the integer values are simply sequential values for each datapoint (i.e. 1,2,3,4 etc).

The category field for the X-Axis is a field called "Date" which comes from a Date Type field in the cube based on a datetime column in the DSV. The properties of the category in the chart are : Group On =Fields!Date.Value and Label =Fields!Date.Value.

Am I missing something obvious?

View 10 Replies View Related

Stored Proc To Get Single Person From A Table Based On Earliest Datetime

Oct 13, 2005

Hi,

I'm having problems with a stored procedure, that i'm hoping someone can help me with.

I have a table with 2 columns - Username (varchar), LastAllocation (datetime)

The Username column will always have values, LastAllocation may have NULL values. Example

Username | LastAllocation
------------------------
Greg | 02 October 2005 15:30
John | 02 October 2005 18:00
Mike | <NULL>

My stored procedure needs to pull back a user name with the following criteria:

If any <NULL> dates send username of first person where date is null, sorted alphabetically, otherwise send username of person with earliest date from LastAllocation

Then update the LastAllocation column with GETDate() for that username.

This SP will be called repeatedly, so all users will eventually have a date, then will be cycled through from earliest date. I wrote an SP to do this, but it seems to be killing my server - the sp works, but I then can't view the values in the table in Enterprise Manager. SP is below - can anyone see what could be causing the problem, or have a better soln?
Thanks
Greg
------------------------------------------------------------------------------
------------------------------------------------------------------------------
CREATE PROCEDURE STP_GetNextSalesPerson AS
DECLARE @NextSalesPerson varchar(100)

BEGIN TRAN

IF (SELECT COUNT(*) FROM REF_SalesTeam WHERE LeadLastAllocated IS NULL) > 0
BEGIN
SELECT TOP 1 @NextSalesPerson = eUserName FROM REF_SalesTeam WHERE LeadLastAllocated IS NULL ORDER BY eUserName ASC
END
ELSE
BEGIN
SELECT TOP 1 @NextSalesPerson = eUserName FROM REF_SalesTeam ORDER BY LeadLastAllocated ASC
END

SELECT @NextSalesPerson
UPDATE REF_SalesTeam SET LeadLastAllocated = GETDATE() WHERE eUserName = @NextSalesPerson


COMMIT TRAN
GO

View 2 Replies View Related

Set Operations (EXCEPT/EXCEPT ALL)

Jul 20, 2005

Hi all,I just start using SQL Server for my project. I have some questionsrelated to set operations. Suppose I have two tables, Table A andTable B, as following.TableA TableB======= =======--------------- ---------------| ID | DATA | | ID | DATA |--------------- ---------------| 1 | Val-01 | | 1 | Val-01 || 2 | Val-01 | | 2 | Val-02 || 3 | Val-02 | | 3 | Val-02 || 4 | Val-03 | | 4 | Val-03 || 5 | Val-04 | ---------------| 6 | Val-05 |---------------In DB2, I can write SQL statements as followingSQL 1:===========================SELECT DATA FROM TableAEXCEPTSELECT DATA FROM TableBAnd the result will beVal-04Val-05===========================SQL 2:===========================SELECT DATA FROM TableAEXCEPT ALLSELECT DATA FROM TableBAnd the result will beVal-01Val-04Val-05===========================1. How can I handle the EXCEPT (ALL) operator in SQL Server?2. Are there equivalent SQL queries for the above SQL queries?Thank youErwin Leonardi

View 4 Replies View Related

MS SQL DB Operations

Mar 31, 2008

I'm still a newbie with MS SQL DB. I was asked to perform some tasks within 3 days at maximum as follows:

1- Refine unique names from over than 80,000 students' names (Firstname, Middlename and Lastname) into a unique table so that we take all those name and translate them from local language to English through data entry employees (a dictionary).

2- Replace local names by English names into a new columns.

3- Creating a procedure that auto generates aliases based on Firstname, Middlename and Lastname as follows:

Assume the name John Edward Smith is found 5 times between 80,000 students, to create a unique ID do the following:

1- FirstnameLastnameint (JohnS).
2- FirstnameinLastname (JSmith).
3- FirstnameLastname (JohnSmith).
4- Firstnameint.Lastname (J.Smith).
5- Firstname.Middlenameint.Lastname (John.E.Smith).

Another precedure also needed:

We have 4 divisions at the establishment, needed to symoblize each division by a letter followed by ( - ) sign as follows:

1- If division = X , generate: x-ID
2- If division = Y, generate: y-ID
3- If divison = Z, generate: z-ID
4- If division =S, generate: s-ID



Can you please provide me with such a procedure to perform this in details?

Thank you

View 3 Replies View Related

Nonlogged Operations

Sep 28, 2000

Hello,

I would like to know if there is a way to disable logging within SQL. (SQL7)
I set all of the obvious options (select into/bulk copy; truncate on checkpoint...) -- and not using SQL Servers conditions set in books online.

Here is the situation:

We have a VB app that updates about 14million records on a monthly basis. The commands are INSERT, UPDATE.. (no select into OR write text) There is no way to use this app that I know using BCP, or bulk insert since we are updating and not simply importing?
So now when this process runs, first the Tempdb fills(problem 1). I shut down SQL and re-initalized the TEmpdb. The data "update" should take ~3 days. Initial run shows the Tempdb filling, then the thread halts. Basically, the application copies records from a user defined "staging" database into a second user database. The second db's transaction log is growing considerable (say 6GB and growing after only a day) (problem2). I am concerned that after resolving the Tempdb from filling (unrestricted size set, and I know Tempdb automatically truncates on checkpoint..) but then we still face the issue to the db that the data is updated will fill out of control!

Ideally, I would like to set a db option that disables logging during this UPDATE statement, in other words operate with no integrety. We backup before so a restore should take care of things in the event. I think this will also aid in performance.

Thoughts on update nonlogged operations if any?

Thanks in advance.
Jason

View 2 Replies View Related

Row By Row Operations In Sqlserver

Sep 15, 2006

hello,

I need to push data from a temporary table into a master table in sql server database(Both tables are in the same database).

I need to follow these conditions.
tables used:
1. temporary table: Temp
2. master table: Master

for every record or row in Temp
check if exists(Temp.field1)in Master.Field1 then
update Master with this row.
else Insert into Master this row.

I performed a research through the net, and found various suggestions. like usage of cursors, usage of while loops etc.
I have to use nearly 50,000 to 60, 000 rows minimum or even more.
Time complexity is also to be considered

I request all who visit this thread to place any possible solutions/suggestions how shall i make this task.

I thank all in advance

View 4 Replies View Related

File Operations

Apr 17, 2007

I need to know, how to rename a file, how to delete a file. how to create a file, all programmatically in Vista.



Thanks in advance,



Frank

View 1 Replies View Related

Batch Operations Of SQL Command.

Jun 6, 2007

Hi,Im trying to write a class that compiles a list of SQLCommands and then executes them all at once. Im trying to reduce the amount of calls to the database.Im also trying just to update the fields which have changed so I cannot use Stored Procedures as that would mean writing way too many stored procedures for every permutation on every table in my database.So Ive decided to build sql commands and then execute them all with one call to the database. When I print the commandtext property of the sqlcommand to the page whilst debugging It shows something like insert into XXX (f1,f2) values (@v1,@v2). Is there any way to see the final sql string, with the @v1 variables replaced by the actual values in the parameters I have added to the sql command?Im building the commands by creating a new sqlCommand. Then I set the commandtext to "insert into XXX (f1,f2) values (@v1,@v2)". Then I Add Parameters to the sqlCommand. My Parameters count is showing the correct value.I want to be sure now that when I go to send these commands to the database as part of one long string that it will work.Thanks,C 

View 3 Replies View Related

Operations Through Stored Procedures

Nov 20, 2007

i write a following stored procedure
create proc prc_BUSINESS_MASTER(@chByMode   Char(1),  @intLIST_ID int=null,@intLISTBUSINESSID int=null,@dtmDATE datetime=null,@dtmEXPDATE datetime=null,@vchSTATUS varchar(10)=null,@vchOFFICE varchar(100)=null,@numCITY numeric =null,@numCOUNTY numeric=null,@numSTATE numeric=null,@numCOUNTRY  numeric=null,@vchSICCODE varchar(50)=null,@numASKINGPRICE numeric =null,@numDOWNPRICE numeric=null,@bitOWNERFINANCE bit=null,@numOWNERFINANCE numeric=null,@numADJ_NETAMOUNT numeric=null,@numSALESAMOUNT numeric=null,@dtmYOE datetime=null,@dtmYRSOWNED datetime=null,@bitBITISACTIVE bit=null,@vchCREATEDBY varchar(50)=null,@dtmCREATEDDATE datetime=null,@vchUPDATEDBY varchar(50)=null,@dtmUPDATEDDATE datetime=null
)
as
set nocount ondeclare @byIntErrDescOut intdeclare @interrno intdeclare @intdupchk intbegin
IF @chByMode NOT IN ('I','U')      BEGIN        SET @byIntErrDescOut = 1        Return -1       END   SET @byIntErrDescOut = 0   /* *************** Insertion Area *************** */ 
 
IF @chByMode = 'I' BEGIN       
IF  @vchSTATUS IS NULL OR @vchSTATUS = ''          BEGIN     SET @byIntErrDescOut = 1     Return -1               END
/*****  Duplicate  checking   ****/ 
 
SELECT @intDupChk = COUNT(1) FROM BUSINESSMASTER WHERE vchLIST_STATUS=@vchSTATUS And vchLIST_OFFICE=@vchOFFICE    IF  @intDupChk <> 0         BEGIN    SET @byintErrDescOut = 5    Return -1             END 
 
insert into BUSINESSMASTER(
intLIST_ID,dtmLIST_DATE,dtmLIST_EXPDATE,vchLIST_STATUS,vchLIST_OFFICE,numLIST_CITY,numLIST_COUNTY,numLIST_STATE,numLIST_COUNTRY,vchLIST_SICCODE,numLIST_ASKINGPRICE,numLIST_DOWNPRICE,bitLIST_OWNERFINANCE,numLIST_OWNERFINACE,numLIST_ADJ_NETAMOUNT,numLIST_SALESAMOUNT,dtmLIST_YOE,dtmLIST_YRSOWNED,bitBITISACTIVE,vchCREATEDBY,dtmCREATEDDATE,vchUPDATEDBY,dtmUPDATEDDATE
)values(@intLIST_ID,@dtmDATE,@dtmEXPDATE,@vchSTATUS,@vchOFFICE,@numCITY,@numCOUNTY,@numSTATE,@numCOUNTRY,@vchSICCODE,@numASKINGPRICE,@numDOWNPRICE,@numOWNERFINANCE,@bitOWNERFINANCE,@numADJ_NETAMOUNT,@numSALESAMOUNT,@dtmYOE,@dtmYRSOWNED,@bitBITISACTIVE,@vchCREATEDBY,@dtmCREATEDDATE,@vchUPDATEDBY,@dtmUPDATEDDATE
)
SET @intErrNo = @@Error          IF (@intErrNo <> 0)            BEGIN     SET @byIntErrDescOut = 2     Return -1            END
/*Insertion Area End*/
 
/*-------Updation----------*/
/* IF @chbyMode = 'U'        BEGIN         --IF @intBuyerId  IS NULL        BEGIN     SET @byIntErrDescOut = 1     Return -1            END 
*/
IF (EXISTS (SELECT * FROM  BUSINESSMASTER    WHERE   intLISTBUSINESSID  = @intLISTBUSINESSID ))  BEGIN 
 
    /*****  Duplicate  checking   ****/ 
SELECT @intDupChk = COUNT(1) FROM BUSINESSMASTER      WHERE intLISTBUSINESSID  = @intLISTBUSINESSID and vchLIST_STATUS=@vchSTATUS     IF  @intDupChk <> 0         BEGIN    SET @byintErrDescOut = 5    Return -1             END 
 
     UPDATE  BUSINESSMASTER         SET   intLIST_ID=@intLIST_ID,dtmLIST_DATE=@dtmDATE,dtmLIST_EXPDATE=@dtmEXPDATE, vchLIST_STATUS=@vchSTATUS,vchLIST_OFFICE=@vchOFFICE,numLIST_CITY=@numCITY,numLIST_COUNTY=@numCOUNTY, numLIST_STATE=@numSTATE,numLIST_COUNTRY=@numCOUNTRY,vchLIST_SICCODE=@vchSICCODE,numLIST_ASKINGPRICE=@numASKINGPRICE,numLIST_DOWNPRICE=@numDOWNPRICE,bitLIST_OWNERFINANCE=@bitOWNERFINANCE,numLIST_OWNERFINACE=@numOWNERFINANCE,numLIST_ADJ_NETAMOUNT=@numADJ_NETAMOUNT,numLIST_SALESAMOUNT=@numSALESAMOUNT,dtmLIST_YOE=@dtmYOE,dtmLIST_YRSOWNED=@dtmYRSOWNED,bitBITISACTIVE=@bitBITISACTIVE,vchCREATEDBY=@vchCREATEDBY,dtmCREATEDDATE=@dtmCREATEDDATE,vchUPDATEDBY=@vchUPDATEDBY,dtmUPDATEDDATE=@dtmUPDATEDDATEWHERE intLISTBUSINESSID = @intLISTBUSINESSID            -- AND WhenUpdated = @ptmsUpdated             SET @intErrNo = @@Error             IF (@intErrNo <> 0)             BEGIN      SET @byIntErrDescOut = 4      Return -1             END       END    ELSE     BEGIN     SET @byIntErrDescOut = 4     Return -1          END      END    End
How can i check this procedure by performing insert ,update operations?
ie., how can i passing and updating informations through stored procedures?
Explain me in detail....

View 2 Replies View Related

Cross Database Operations

May 6, 2008

Hi,
I'm trying to get data from several databses of different kinds (Sql Server and Oracle) and from different servers - is that possible ?
If not - is there any way to copy some data from one database to another - like tables and their content (or partial content) ?

I tried to use "select name from <database name>..sysobjects where xtype = 'U'" but I get security error.

thanks,
Naama

View 2 Replies View Related

Thoughts On Asynchronous Operations With SLQ Ce

Jan 3, 2007

I noticed that the current SLQCe driver does not offer support for the APM(Asynchronous Programming Model). Are there any plans to do this in the future? In light of the lack of APM functionality doe anyone have any ideas or thoughts on how async operations could be done, or if they are even needed in the context of applications that use SQL Ce

View 4 Replies View Related

String Operations On Numeric Value And ODBC

Apr 10, 2001

This statement works fine in T-SQL, but when executed thru ODBC results in a <NULL>. How can I get this to work thru ODBC....? Im guessing I need to use CAST, but not sure how the sytax would be, my attempts have worked but still resulted in a <NULL>...

UPDATE mytable SET
switch = left(switch, 3) + '1' + right(switch , len(switch) -4)
WHERE blah = blah


(switch is a Numeric field)

Thanks,Adrian

View 1 Replies View Related

Perform Several Operations In 1 ALTER TABLE?

Mar 1, 2007

Hi there. Does anyone know of a why to perform several operations on a table within only 1 ALTER TABLE statement? I haven't found anything to date and don't even know if it's possible.

Thanks,

Angel

View 2 Replies View Related

This Is Related To Microsoft Operations Management

Jun 4, 2007

We would like to use MOM to monitor every problem in SQL Server. I was trying to find all the MOM rules corresponding to severity 17 to severity 25 errors. But there are a lot of the errors don't have the matching MOM rules, I wonder if someone can help me or direct me to the proper place.



For example,



error 8653, severity 17. Warning: The query processor is unable to produce a plan because the table '%.*ls' is marked OFFLINE



I can't find corresponding MOM rule for it.





Thanks in advance,

Rose

View 3 Replies View Related

Analysis :: Backend Operations To Run MDX Query

Oct 13, 2015

Whenever we run the mdx query in SSMS, how it will fetch the data from cube.

Using XMLA script used to fetch the data or any thing else ..

View 3 Replies View Related

Help W/Disabling FK Constraints For Batch Operations

May 2, 2006

HI all,

I'm trying to have a SProc that will initialize a database for me. This db is in development (I'm primarily writing SSIS packages, atm), and I constantly need to truncate the tables, then re-add a dummy/unknown row (PK/Identity value = 1). Of course, I need triggers not to fire (got that part working), and FK constraints to be bypassed temporarily -- that's the problem.

Here's where I'm at:

----------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[_InitializeDB]
AS

SET NOCOUNT ON

DECLARE @name varchar(255)
DECLARE @sql nvarchar(255)

DECLARE tables CURSOR FOR SELECT [name] FROM [sysobjects] WHERE [type]='U' AND [name]<>'sysdiagrams'

OPEN tables
FETCH NEXT FROM tables INTO @name
WHILE @@FETCH_STATUS=0
BEGIN
SET @sql = 'ALTER TABLE ['+ @name + '] NOCHECK CONSTRAINT ALL'
EXEC sp_executeSQL @sql
SET @sql = 'DISABLE TRIGGER ALL ON [' + @name + ']'
EXEC sp_executeSQL @sql
SET @sql = 'TRUNCATE TABLE [' + @name + ']'
EXEC sp_executesql @sql
BEGIN TRY
SET @sql = 'INSERT INTO [' + @name + '] (Active) VALUES (0)'
EXEC sp_executeSQL @sql
END TRY
BEGIN CATCH
PRINT @sql + ':'
PRINT ERROR_MESSAGE()
END CATCH
SET @sql = 'ENABLE TRIGGER ALL ON [' + @name + ']'
EXEC sp_executeSQL @sql
SET @sql = 'ALTER TABLE ['+ @name + '] CHECK CONSTRAINT ALL'
EXEC sp_executeSQL @sql
FETCH NEXT FROM tables INTO @name
END

CLOSE tables
DEALLOCATE tables
----------------------------------------------------------------------------------

Running this Sproc produces (for the first ref'd table):

Msg 4712, Level 16, State 1, Line 1
Cannot truncate table 'Person' because it is being referenced by a FOREIGN KEY constraint.

View 4 Replies View Related

Skip Foreign Key Violations During Insert Operations?

May 12, 2014

I'm trying to optimize a few batch import procedures we use in our processes.

It currently works like this:

1) Cursor loop cycles through all data to be imported from IMPORT table

2) For every record there is an attempted insert to PROD table in a TRY-CATCH check to see whether the record would pass all the primary key and foreign key constrains in PROD table

3) Only those that pass the TRY-CATCH check gets imported into PROD table

4) Every row gets logged into a separate LOG table, either with a comment like "Import OK" or "Error: foreign key violation in field 'my_id'"

The thing is, the procedure runs fine when I'm importing several thousands of records, but when it comes to hundreds of thousands, the speed becomes an issue, as I currently get 20 records per second and slowing...

There is no other code in that procedure, no queries. Just the Cursor cycle and the try-catch check.

PS: I'm using MS SQL Server 2005.

View 4 Replies View Related

SQL Server 2008 :: How To Perform Sum And Count Operations

Sep 9, 2015

I created a report where collected payments are listed by each collector from month to date.Everything Looks ok on the reporting side until a requirement came up where I am Also supposed to list the total number of payments collected by each collector (the count) and also the (total sum). If you look at the attached excel you would see two tables, I am getting the first table, 2nd is the one I want expected). How do I perform sum and count operations?

ALTER PROC USP_PaymentsByCollector
(
@CollectorName AS varchar(20) = NULL,
@CollectorCode AS varchar(20) = NULL,
@LoanID AS varchar (20) = NULL
--@StartDate AS DATETIME = NULL,
----@EndDate AS DATETIME = NULL

[code]....

View 3 Replies View Related

Help With The Security/Login/User Area Of Operations

Jul 23, 2005

Currently studying for 70-229.I'm trying to understand how security for users is managed in SQLServer. I've been using SQL Server for a few years now, but withoutinvestigating the bits that "just work".So, here's the scenario. This is more or less how I create all myapplications (which these days are all ASP.NET).I have a database called "TESTDB" (original, huh?)Now, I want to create a method for users to access this database, so Iopen EM, locate and expand the node for the server containing thedatabase, and open the "Security" node. Click on the "Logins" leaf,and in the pane right-click and select "New Login.."On the "General" tab I enter "TESTDBLOGIN" as the Name.Select "SQL Server Authentication", and put in a password.In the drop-down list of databases select "TESTDBLOGIN"Ignoring the "Server Roles" tab, I go to the "Database Access" tab andscroll down until I can see the "TESTDB" database. Check the "Permit"checkbox, and lo!, the "Database Roles for TESTDB" list is populated,with "public" already ticked. I check the "db_owner" box, and press"OK". It asks me to confirm the password, and once that's done there'sa new login called TESTDBLOGIN. What's more in "Users" leaf in the"TESTDB" database node there's a new user called "TESTDBLOGIN".All well and good. I can now create a connection using this login anddo more or less what I want in the TESTDB database.But.If I click the "Users" leaf in the "TESTDB" node, there are two users -"dbo" and "TESTDBLOGIN". If I right-click the "TESTDBLOGIN" user, Ican see that it has Database Role Memberships for the "public" and the"db_owner" roles. But if I examine the permissions on these two roles(by selecting the row, and then pressing the "Permissions" button) Ifind that there are permissions set for EITHER role - all the checkboxes are blank!So, how is it that I can do SELECT, UPDATE, INSERT and DELETEoperations via this login/user?Sorry it all took so long - I just wanted to get it right.ThanksEdward--The reading group's reading group:http://www.bookgroup.org.uk

View 3 Replies View Related

The Datasource , 'db Name', Contains An ImpersonationMode That That Is Not Supported For Processing Operations.

Nov 17, 2006

I get the below error when i try to process my cubes:

The datasource , 'local - SRDB', contains an ImpersonationMode that that is not supported for processing operations.



I have tried all 4 impersonation modes, but the same error comes from all. i created a new connection , and when i click "test" it says test successful, but the new connection throws the same error. anyone have any ideas?

View 24 Replies View Related

Reporting Services :: Scheduled Operations Cannot Be Created

Sep 17, 2015

We use Reporting Services in native mode in our environment and have several data-driven subscriptions on reports. Somehow not all of the subscriptions can be executed, this seems totaly random and doesn't always apply to the same report/schedule. In the event viewer, I can see the error message : "Scheduled operations cannot be created. SQL Server Agent is not running" ....

But the Agent is in running state and there are no logs that the Agent has stopped or started again. A few minutes later, everything looks okay again and the rest of the scheduled subscriptions are executed.

This doesn't happen every day but 3 or 4 times a week. The following version of SQL Server is installed :

Microsoft SQL Server 2008 R2 (SP2) - 10.50.4295.0 (X64)   Oct 18 2013 19:22:52   Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ).

What causes these problems or where to look to determine the cause of this error?

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved