SQL Server 2008 :: Use Top N For Select / Delete In A While Loop?

Jul 27, 2015

Can I safely use top n select/delete in a while loop? For example:

declare @FieldVal int
while (select count(*) from @MyTempTable) > 0
begin
select top 1 @FieldVal = FieldVal from @MyTempTable
-- process @FieldVal then delete the row
delete top 1 from @MyTempTable
end

I like the simplicity of the above approach as long as it's reliable and there aren't any gotchas that I may not be aware of.

View 9 Replies


ADVERTISEMENT

SQL Server 2008 :: Difference Between FOR LOOP And FOREACH LOOP?

May 28, 2010

difference between FOR LOOP and FOREACH LOOP with example(if possible) in SSIS.

View 4 Replies View Related

SQL Server 2008 :: Maintenance Plan Delete History Trying To Delete Wrong Files

Sep 11, 2015

I have some simple files but they are failing because the delete history task is failing as it is looking for files in a non existent directory.

It is looking for files in C:Program FilesMicrosoft SQL ServerMSSQL10_50.INSTANCEMSSQLLog whereas it should be looking in C:Program FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLLog

how I can get this corrected so I can get the Maintenance Plans to run correctly.

I have tried deleting and recreating the Plan but to no avail

View 0 Replies View Related

SQL Server 2008 :: Loop To Insert 0s Into Table

Oct 22, 2015

I have a problem where I want to create a loop in my script to insert 0's into my table.

I have a temp table with a list of company codes.

SELECT CODE FROM ##SENData GROUP BY CODE

This produces the following;

CODE
00C
00D
00K
00M
00Q
00T
00V
00X (there are 110 of these codes)

I want to insert data into a different table in the following format.

+------+------------+-------+---------+
| CODE | Month | Value | Measure |
+------+------------+-------+---------+
| 00C | 01/09/2015 | 0 | HAR-01 |
| 00D | 01/09/2015 | 0 | HAR-01 |
| 00K | 01/09/2015 | 0 | HAR-01 |
| 00M | 01/09/2015 | 0 | HAR-01 |
| 00Q | 01/09/2015 | 0 | HAR-01 |
| 00T | 01/09/2015 | 0 | HAR-01 |
| 00V | 01/09/2015 | 0 | HAR-01 |
| 00X | 01/09/2015 | 0 | HAR-01 |
+------+------------+-------+---------+

The month will be set from a declared variable and the others will just be hard coded.

View 3 Replies View Related

SQL Server 2008 :: SSIS - For Each Loop Through Multiple Servers

Jan 30, 2015

I have an SSIS job that dynamically loops through each server, grabbing data for typical DBA reporting, like diskspace, and errorlogs. If the server is down for whatever reason the SSIS package fails. Is there any way I can prevent the SSIS package from failing if one of the servers is down?

View 1 Replies View Related

SQL Server 2008 :: Iterate Query Using A Loop As Many As 5 Times Max?

Mar 20, 2015

If exists (select fieldID from #tmploginfo where status <> 0
group by fieldID
having count(*) > 0)
begin
backup log rdb to disk = N'C:
db1.trn'
End

I want to iterate this query using a loop as many as 5 times max.

View 3 Replies View Related

SQL Server 2008 :: How To Increase Performance Of Insertion SP In While Loop

Aug 13, 2015

WHILE (@MyLoop3 > 0)
BEGIN
SELECT Top 1 @UploadId = UploadId,@FirstName = (CASE WHEN FirstName = '' THEN @Update ELSE FirstName END),
@LastName = (CASE WHEN LastName = '' THEN @Update ELSE LastName END),
@Claim = (CASE WHEN Claim = '' THEN @Update ELSE Claim END),
@Insurer = (CASE WHEN Insurer = '' THEN @Update ELSE Insurer END),
@InsurerBranch = (CASE WHEN InsurerBranch = '' THEN @Update ELSE InsurerBranch END),

[Code] .....

View 3 Replies View Related

SQL Server 2008 :: Compare Data / Loop Through Dates And Insert Into Table

Sep 21, 2015

I have three tables:

"PaymentsLog"
"DatePeriod"
"PaidOrders"

As per below

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PaymentsLog](

[Code] ....

Is there a way to look at the DatePeriod table and use the StartDtae and EndDate as the periods to be used in the select statement and then cursor through each date between these two dates and then insert the data in to the PaymentsLog table?

View 3 Replies View Related

SQL Server 2008 :: MERGE And Delete From Target

Mar 12, 2015

I'm not even sure this is possible but I'm using MERGE in a process that has 3 source tables (the process steps through each source table sequentially) and I need to delete from the Target database occasionally.

My current code is

sqlMerge = "MERGE " + TableName + " AS target USING @CData AS source" +
" ON target.TotRsp = source.TotRsp AND target.ClientRef = source.ClientRef AND target.dbPatID = source.dbPatID" +
" WHEN MATCHED THEN" +
" UPDATE SET dbPatFirstName = source.dbPatFirstName, dbPatLastName = source.dbPatLastName,

[Code] ....

The Target db data is made up from several different clients and when the MERGE runs it uses TotRsp, ClientRef and dbPatID to uniquely match a source row to the target row and if no match it inserts the source row.

My problem is that when this runs with Source A first, it will delete all merged data from Source B & C. Then when Source B runs it will insert all Source B data but delete all from A & C and so on.

Is there way that that I can include additional clauses into NOT MATCHED BY SOURCE THEN so it knows only to delete when data has come from say Source A. Once the data is in the target table there is no reference to which source table it came from tho.

If there isn't a solution I suppose I could always add an extra column to the target db to indicate which source it came from and then have something like

NOT MATCHED BY SOURCE AND t.Source = 'SourceA'.

That's quite a bit of work my end to do that tho so I'd like to be sure it works.

View 1 Replies View Related

SQL Server 2008 :: Delete Before Insert Trigger Statement

Apr 6, 2015

What statement do I use, as part of an insert trigger, to insert xml data from the xml database to a flat file database, to check if a record with a specific ID exists to delete first then insert the changed record, instead of adding the changes or an updated from the original xml database.

What I’m trying to do is take the xml formatted data out of one sql server database and insert the data only in that xml into a another sql database. So I can play with the data.

Problem is if the data in the xml is updated or changed for a specific record on the original xml database then the trigger inserts another copy into the created database (which I don’t want).

This is on SQL Server 2008R2.

View 2 Replies View Related

SQL Server 2008 :: Job To Delete All Records Then Copy All From Another Table?

Apr 22, 2015

I am using a SQL Server Agent jobs that run each morning to update the records in a table to match what they should be for that day. I built them and tested it using a test table called "testtable1". It worked fine. But when I switched over to our production table, it fails saying the table has to be decaled. What would be the difference. The production table has a "@" in front of the name, is that causing issues?

USE [Live_build]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
BEGIN
DELETE
FROM @ZIPLIST
INSERT INTO @ZIPLIST
SELECT * FROM tblZip3DSWed;
END

View 4 Replies View Related

SQL Server 2008 :: Delete Duplicate Rows From ANY Table

Jul 31, 2015

Is there is 'fairly' simple query to delete duplicate rows from ANY table ?

A script which removes duplicates from a table, when a table_name is supplied.

View 9 Replies View Related

SQL Server 2008 :: Why CDC Returning Insert / Delete When UPDATE A Row In Table

Mar 15, 2013

I am experimenting with using CDC to track user changes in our application database. So far I've done the following:

-- ENABLE CDC ON DV_WRP_TEST
USE dv_wrp_test
GO
EXEC sys.sp_cdc_enable_db
GO

-- ENABLE CDC TRACKING ON THE AVA TABLE IN DV_WRP_TEST
USE dv_wrp_test

[Code] ....

The results shown above are what I expect to see. My problem occurs when I use our application to update the same column in the same table. The vb.net application passes a Table Valued Parameter to a stored procedure which updates the table. Below is the creation script for the stored proc:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from sysobjects where id = object_id('dbo.spdv_AVAUpdate') and sysstat & 0xf = 4)
drop procedure dbo.spdv_AVAUpdate

[Code] ....

When I look at the results of CDC, instead of operations 3 and 4, I see 1 (DELETE) and 2 (INSERT) for the change that was initiated from the stored procedure:

-- GET CDC RESULTS FOR CHANGES TO AVA TABLE
USE dv_wrp_test
GO
SELECT *
FROM cdc.dbo_AVA_CT
GO

--RESULTS SHOW OPERATION 1 (DELETE) AND 2 (INSERT) INSTEAD OF 3 AND 4
--__$start_lsn__$end_lsn__$seqval__$operation__$update_maskAvaKeyAvaDescAvaArrKeyAvaSAPAppellationID
--0x0031E84F000000740008NULL0x0031E84F00000074000230x02119Test26NULL
--0x0031E84F000000740008NULL0x0031E84F00000074000240x02119Test36NULL
--0x0031E84F00000098000ANULL0x0031E84F00000098000310x0F119Test36NULL
--0x0031E84F00000098000ANULL0x0031E84F00000098000420x0F119Test46NULL

Why this might be happening, and if so, what can be done to correct it? Also, is there any way to get the user id associated with the CDC?

View 7 Replies View Related

SQL Server 2008 :: Can Delete Contents Of Update-cache Folder

Sep 26, 2013

this directory is over 2gb

Program FilesMicrosoft SQL Server100Setup BootstrapUpdate Cache

can you delete the contents safely?

View 1 Replies View Related

SQL Server 2008 :: Restoring Database - Delete Data From Partitions

Feb 20, 2015

I am restoring a database with 10yrs worth of data which have monthly partitions but i would like to keep only 5yrs of data after the restore is done, what is the best/faster approach to delete the 5yrs data without deleting the partitions as that may cause the db in accessible.

View 9 Replies View Related

SQL Server 2008 :: How To Delete Or Drop Index To Free Up Space

May 31, 2015

I am new to mssql server. There is a table on one of my databases that occupies a lot of space. And the space usage is as follows: (all values in KB)

reserved: 42329064
data: 16272288
index: 26050032
unused: 6744

This table takes up almost 80% of my database size, and the information is this table just captures the time spent by a user on the website(not very critical data)

I would like to know how to delete the entire index (which is what is occupying most space) to free up disk space. the index is a clustered index.

View 3 Replies View Related

SQL Server 2008 :: Archive And Delete Old Records In Table With No Date Column

Feb 4, 2015

I have these two tables Log and CategoryLog, I need to archive records older than 13 months in these two tables to two separate tables and then delete the archived records from Log and CategoryLog tables. The problem is that only 'Log' table has a date column, the other table CategoryLog does not have any date column. But the two tables are connected by a column(LogID). How to archive the data and then delete the archive data from both tables.

View 9 Replies View Related

SQL Server 2008 :: Find All Transaction (insert / Delete / Update) On A Database For A Day?

May 8, 2015

i would like to know it's possible to find all transaction(insert, delete,update) on a database for a day. if yes what can i do.

View 2 Replies View Related

SQL Server 2008 :: Error - Value Does Not Fall Within Expected Range In Delete Query?

May 28, 2015

I have a execute sql task which insert data into a table, but before that I need to make sure no data is available for particular date. we have a table where we are defining date for which date we want to data, and we are fetching that particular date using ssis variable 'Date'. today I was trying to load data dor '2015-05-10'. But it gave me error like '[Execute SQL Task] Error: "Value does not fall within the expected range.'. Below are the my execute sql task query:

delete from STG_Shipped_Invoiced
where Transaction_Date=?
INSERT INTO STG_Shipped_Invoiced (div_Code, inv_inv_id, tot_Net_Amt,
trans_date, trans_type, Created_date, Transaction_Date)
select inv.DIV_CODE as Div_Code, inv.INV_ID as inv_inv_id, inv.TOT_NET_AMT as Tot_Net_Amt,

[Code] ....

Here I have defined a variable 'Date', where we are passing the date. Am i doing anything wrong with the delete query?

View 0 Replies View Related

SQL Server 2008 :: Making Use Of A Large Transaction File To Delete Records?

Jun 5, 2015

Currently we has a database of size about 300G. Because our backup system failed some time past we were left with a transaction log file which grew to about 160G. However our backups are working again and everything is working fine. My understanding is that now the transaction log file is practically empty but the capacity remains at 160G.

When you delete records the deleted transactions are going to get logged to the transaction file. My understanding is when a backup is done these transactions get discarded out of the transaction file.

could I make use of this relatively large transaction file and start deleting transactions without out actually adding to the transaction file size.

The plan is to delete records from logging tables that are not referenced to by any other table without this increasing the transaction log file.For example over a period of a few weeks we can delete a chunk of records from a table. Then after it has completed a backup we can delete another chunk of records out of this table until we have got the table down to the records that we now need.Will this work?

View 2 Replies View Related

SQL Server 2008 :: How To Delete Tables In Database Whose Table Names Match A Criteria

Jul 22, 2015

The database has approx. 2500 temporary tables. The temp tables match a pattern such as APTMP... I tried deleting the tables in SSMS with the statement, Delete from Information_Schema.tables where substring(table_name,1,5) = 'APTMP' This returns the error message"Ad hoc updates to system catalogs are not allowed".

What is the correct way to delete a group of tables whose name match a pattern from within SSMS?

View 9 Replies View Related

SQL Server 2008 :: Query To Delete All Backup Files Older Than A Specific Date?

Jul 29, 2015

I want to delete all backup files from a folder older than a specific date. But if I use the beklow query, I need to pass how many days of older backup files I need to delete whereas in my case, I dont know how many days/month/syears of old backup files are there in the backup folder.

EXEC xp_cmdshell 'FORFILES /p c:BACKUP /s /m *.sql /d -30 /c "CMD /C del /Q /F @FILE"'

View 2 Replies View Related

SQL Loop Delete

Feb 15, 2008

Hi i need a delete by id on a loop but not sure how?

DECLARE

@NEWIDFIELD INT

select @NEWIDFIELD = TI_ID
FROM TRANSIT...T_TBL_TRANSIT
WHERE DATEDIFF(m, TI_Date, getdate())>12


===LOOP THROUGH THE TI_ID FROM THE QUERY ABOVE=====

BEGIN

DELETE FROM TRANSIT...T_TBL_TRANSIT
WHERE TI_ID = @NEWIDFIELD


END

View 12 Replies View Related

Delete With Loop

Dec 5, 2007



Hi All,

I have the following table:


CREATE TABLE #Temp
(DepID INT,
EmpID INT,
DateAdded DateTime,
DateAdded DateTime
)

INSERT INTO #Temp
VALUES (185650, 1156619, '2007-10-15 00:00:00.000', '2007-10-15 00:00:00.000')
INSERT INTO #Temp
VALUES (185650, 1156630 , '2007-10-15 00:00:00.000', '2007-10-15 00:00:00.000')
INSERT INTO #Temp
VALUES (185650, 1156632 , '2007-10-15 00:00:00.000', NULL)
INSERT INTO #Temp
VALUES (185650, 1156633 , '2007-10-15 00:00:00.000', '2007-10-15 00:00:00.000')
INSERT INTO #Temp
VALUES (48897, 1157075, '2007-10-16 00:00:00.000', '2007-10-16 00:00:00.000')
INSERT INTO #Temp
VALUES (48897, 1157097 , '2007-10-16 00:00:00.000', '2007-10-16 00:00:00.000')


SELECT * FROM #Temp


I'd like to delete the MIN(EmpID) that have same dateadded and same dateremoved until there is only one per each DepID left in the table.

I did the following query to delete the MIN(EmpID) for those employees that are added and removed at the same date but it will have to be done several times since i have more than 2 EmpID per DepID. What is the best way to get only one EmpID per DepID if they were added at the same time and removed at the same time?

DELETE FROM #Temp
WHERE EmpID IN
(
SELECT MIN(T1.EmpID) FROM #Temp T1
INNER JOIN #Temp T2
ON T1.DepID = T2.DepID and T1.EmpID !=T2.EmpID and T1.DateAdded = T2.DateAdded
and T1.DateRemoved = T2.DateRemoved
WHERE T1.Dateadded = T1.DateRemoved and T2.DateAdded = t2.DateRemoved
GROUP BY T1.DepID
)

The result i would like to see is

/*------------------------

SELECT * FROM #Temp

------------------------*/
DepID EmpID DateAdded DateRemoved
185650 1156632 2007-10-15 00:00:00.000 NULL
185650 1156633 2007-10-15 00:00:00.000 2007-10-15 00:00:00.000
48897 1157097 2007-10-16 00:00:00.000 2007-10-16 00:00:00.000

Drop table #Temp


Thanks,
Phee

View 1 Replies View Related

Error SQL Server When Try To Select Or Delete Or Add New

Sep 4, 2007

when i try to get data or insert new from some table.
SQL show this message error
---------------------------------------------------------------------------
Server: Msg 3624, Level 20, State 1, Line 1

Location: q:SPHINXNTDBMSstorengdrsinclude
ecord.inl:1447
Expression: m_SizeRec > 0 && m_SizeRec <= MAXDATAROW
SPID: 52
Process ID: 2116
Connection Broken
-------------------------------------------------
how to fix this problem ? These table have around 2,900,000 records.

thanks.

View 1 Replies View Related

SQL Search :: Delete Multiple Lines Using Loop

Aug 31, 2015

How can I run through an array of ID's and delete the fields associated to it in a single table?  I have a lot of bad data that needs to be removed.  BTW, I'm using the SQL Server Management Studio to do this.

I'm currently doing by hand by using the following.

USE database;
DECLARE @id integer
SET @id = XXXXX
DELETE FROM table WHERE id = @id;

I would like to use the same code but with a slight variation to support an array.

View 4 Replies View Related

SQL Server 2008 :: How To Select First Name Only

May 30, 2015

There is a column for Name with data type varchar 50 the input data is like Alok Kumar, Sunita kuamri, Rohit Gupta Like that. The column contains the data as Combination of First name and second name.I would like to write a select query for selecting first part of name like Alok, Sunit, Rohit and so on only, ignoring the second part of name.

View 3 Replies View Related

SQL Server 2008 :: Using Encrypted Value In Select-where

Mar 6, 2015

The passwords in table 'users', column 'passwordencrypted' are encrypted. Someone enters a password and I'd like to compare if it is correct. The syntax below seems ok but nothing is returned. Why not?

OPEN SYMMETRIC KEY mykey DECRYPTION BY CERTIFICATE mycert;
DECLARE @mypw varchar(300);
SET @mypw = 'test';
SELECT * FROM users WHERE passwordencrypted = EncryptByKey(Key_GUID('mykey'), @mypw);
CLOSE SYMMETRIC KEY mykey;

View 3 Replies View Related

SQL Server 2008 :: Merge 2 Select Statements

Aug 25, 2015

SELECT
part.num, woitem.qtytarget AS woitemqty,

(SELECT LIST(wo.num, ',')

FROM wo INNER JOIN moitem ON wo.moitemid = moitem.id
WHERE moitem.moid = mo.id) AS wonums, mo."USERID" AS mo_USERID

[Code] ...

View 5 Replies View Related

SQL Server 2008 :: How To Write A SELECT Statement To Get Data From A Linked Server

Feb 23, 2015

I have the linked server connection created and works perfectly well. I mean I am able to see the tables while I am on my database.

how do I write a SQL statement to reference the linked server ?

I tried the following:

Select top 100 * from casmpogdbspr1.MPOG_Collations.dbo.AsaClass_Cleaned

Then I get the error message....

Msg 7314, Level 16, State 1, Line 1

The OLE DB provider "SQLNCLI10" for linked server "casmpogdbspr1" does not contain the table ""MPOG_Collations"."dbo"."AsaClass_Cleaned"". The table either does not exist or the current user does not have permissions on that table.

View 2 Replies View Related

SQL Server 2008 :: Select Alternate Number Of Rows?

Jan 28, 2015

A simple Query to select alternate rows from a table ?

View 9 Replies View Related

SQL Server 2008 :: Parsing Data To Select Certain Values From XML

Mar 13, 2015

I have results that are XML data and I am trying to figure out how to parse the data to select certain values from the xml.

example
<InformationRequest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" teamid="TEAM003341507" playerid="PL341508" gameid="G000000852" playertype="Starter" FolderName="Test" CurrentYear="2015" Ultimateid="P00000688505" xmlns="http://schemas.sports.com/Messages/Stats" />

I would like to write a statement that just pulls the game id G000000852. So just the id right of gameid=.

Not really sure where to start. Table is GAME, and column is XMLDATA.

View 0 Replies View Related

SQL Server 2008 :: Join Another Table But With Select Conditions?

Mar 24, 2015

I have this sql....

Select
DISTINCT p.dbPatID, p.dbpatfirstname, p.dbPatLastName,
s.dbSchTypeCnt as SchDetailType, t.dbSchTypeCnt as SchTypeType,
ISNULL(r.dbStatusDesc, 'No Ref') AS dbStatusDesc,
ISNULL(t.dbSchTypeCode, 'No Ref') AS dbSchTypeCode,
ISNULL(t.dbSchTypeDesc, 'No Ref') AS dbSchTypeDesc,

[code]....

however, I only want the lastest a.dbPatApptTime and only when a.dbPFStatus = 1 and a.ClientRef = 'EPS'

So the stand alone sql could be....

Select Top(1) dbPatApptTime as LastVisitDate, dbSchTypeDesc as LastVisitDesc
from appointments
where dbPFStatus = 1 and clientref = 'EPS'
order by dbPatApptTime desc

I'm just not sure how to incorporate that into my sql or whether there is a better way,

View 9 Replies View Related







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