Can A DELETE's OUTPUT Rowset Be Ordered?
Oct 19, 2007I'd like the "OUTPUT DELETED.* INTO target table" resulting from a DELETE to occur in the same order as the clustering key of the target table. Is this possible?
View 6 RepliesI'd like the "OUTPUT DELETED.* INTO target table" resulting from a DELETE to occur in the same order as the clustering key of the target table. Is this possible?
View 6 RepliesCurrently running Sql Server 2005Is it possible to issue the delete command and capture the affected rows asxml types that will be stored in an audit table with an xml column?Something along the lines of:delete from source_tableoutput(deleted.*into audit_table (xml_audit_column)for xml auto)where source_table.column = @delete_value
View 1 Replies View RelatedHello Experts. You may have more luck at this than me.
I am interested in finding the quantity of items that were ordered alone. I have an orderid field and a product field. So the count of the orderid has to equal one and the have them grouped by product.
Example of how data looks like
I am looking for transactions like orderid 3 and 5.
OrderID
Product
1
hotdog
1
burger
1
taco
2
burrito
2
snack
2
chips
3
burger
4
hotdog
4
burger
4
taco
5
burrito
6
snack
6
chips
When i run
SELECT product, count(orderid)
From Table
Where BusinessDateID = 20060725
group by product
having (count(orderid)=1)
I only get back items that were only sold once.
I am looking for a result that looks like this
Product
Ordered alone
hotdog
2
burger
3
taco
4
burrito
32
snack
12
chips
76
I need to export data in a specific order (e.g. the order in which the data was inserted into the table). My BCP was doing this then just started exporting in random order. I know that SQL 7 doesn't guarantee return order unless specified by an ORDER BY clause. However, that's not possible with BCP unless you use the command line BCP with the QUERYOUT option. That's my problem. I'm using the BulkCopy object in DMO and I don't see an option to order the data or use a query with an order by statement. Any suggestions?
--Buddy
Hi all,
I feel like I'm missing something really simple here...
I'm trying to write an sp to return a list of countries alphabetically to populate a web drop-down list in a form. However, since most people using the form will be from USA, I want "USA" to appear as the first row, then the rest should be alphabetical, e.g. ("USA", "Afghanistan", "Albania"... "Zimbabwe")
I'm using a UNION query, but it's ordering the result set so that USA appears alphabetically, not as the first row. I'm not using an ORDER BY clause.
Here's the code I'm using:
CREATE PROCEDURE GetCountries AS
SELECT Country_Name
FROM Countries
WHERE Country_Name = 'USA'
UNION
SELECT Country_Name
FROM Countries
WHERE Country_Name <> 'USA'
GO
I also tried selecting into a temp table and doing a UNION that way, but got the same results.
We have a 10 digit primary key value in this format: M000123456. Theorder for this key is first determined by positions 3 and 4 in thisexample, then positions 1 and 2. So a brief sample of correct orderingwould look like this:M000001501M000011501M000021501M000001601M000011601M000021601Now my question: how can I use a BETWEEN (or > and <) in my WHEREclause to get a range of values for this column? I use the followingORDER BY clause to control how the results are sorted, but I can't getthe same logic to work with BETWEEN in a WHERE clause.ORDER BY SUBSTRING(<fieldname>, 7, 2), SUBSTRING (<fieldname>, 5, 2)How do I return values between M000011501 and M000011601 for example?
View 3 Replies View RelatedI€™m trying to follow examples from: http://www.sqlmag.com/Articles/ArticleID/49240/49240.html?Ad=1 for an update statement that needs to run in a specified order.
Here€™s my problem:
I have a table:
TopicActivity
PK €“ DayNum int (this is a date in YYYYDDD format)
PK €“ TopicId int
Visits int
LifetimeVisits int
LifetimeVisits is a new column that I want to calculate the value using the previous Visits column data.
Sample Data:
DayNum TopicId Visits LifetimeVisits
2008001 1 5 0
2008002 2 1 0
2008002 1 3 0
2008003 1 10 0
I want the end result to look like this:
DayNum TopicId Visits LifetimeVisits
2008001 1 5 5
2008002 2 1 1
2008002 1 3 8
2008003 1 10 18
Here is the query I€™ve been trying:
WITH ordered AS
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY TopicId ORDER BY DayNum) AS RowNum
FROM TopicActivity
)
update ordered set
ordered.LifetimeVisits = ordered.Visits +
isnull((select o2.LifetimeVisits
from ordered as o2
where o2.TopicId = ordered.TopicId
and o2.RowNum = (ordered.RowNum - 1)),0)
The update doesn€™t seem to be happening in order as LifetimeVisits seems to have random results every time I run the query. (Usually the first couple of rows are right. I€™m dealing with thousands of records) I can€™t use a cursor as the query takes way to long.
I'm running SQL Server 2005.
hi,
i am a newcomer and a freshman in asp.net. i am now writing a web-based system for SME as my final year project. i am going to use sql server and asp.net in C# to perform my final year project.
as asp.net is new for me, i would have some simple problems to ask.
1. in the project, i would like the system can automatically generate the enquiry number for each new order input to the system. for example today is 05 July 2006, the enquiry number would like 2006211xxxx, where 2006 is year, 211 is the day count start from 1 Jan and xxxx is the random number/ ordered number. how can i implement this? i even don't know how to generate the ordered number. could anyone help me
2. if there is an unknown test sample in each order input. as the sample number for each order is different, how can i set a flexible table that can have different number of rows for user to input the test result.
thanks
Rgds, universe
Installed the Northwind database for data to practice with. I'm trying to combine data from several tables to make the orders table more readable. Meaning, I'm trying to replace the EmployeeID field with the combination of the firstname and lastname fields from the Employees table. Everything works fine until I try to sum the Unit price field from the [Order Details] table. Using just a SUM() function or the Select statement below causes the error and any combination of fields in the Group By command don't correct it. It's clear that I'm doing something wrong, I'm just not sure how to get the data I want or use the group by command properly. Query below:
Select o.OrderID, c.companyName, e.firstname + ' ' + e.lastname EmployeeName, o.orderdate, s.companyName,
o.Freight, o.shipName, o.ShipAddress, (Select Sum(od.UnitPrice) from [Order Details] od where od.OrderID = o.OrderID)as Amount
from orders o, customers c, Employees e, Shippers s, [Order Details] od
where o.CustomerID = c.CustomerID
[Code] ....
Running the first query (with the select statement) works, but returns a row for each of the the items that was ordered for that OrderID and NOT using the Group By. I would like to have the SUM() of the items ordered in one row. Is this possible?
When a nonunique nonclustered index is built on top of a clusteredindex, is it guaranteed that the bookmark in the nonclustered indexwill be kept in the same order as the clustered index?Here's an example to demonstrate my question:CREATE TABLE indextest (col1 int NOT NULL,col2 int NOT NULL,col3int,col4 int)ALTER TABLE indextest ADD PRIMARY KEY CLUSTERED (col1,col2)CREATE INDEX ix_indextest ON indextest (col1,col3)GOINSERT indextest VALUES (1,2,1,1)INSERT indextest VALUES (1,3,2,1)INSERT indextest VALUES (1,4,2,1)INSERT indextest VALUES (2,1,1,1)INSERT indextest VALUES (1,1,1,1)SELECT col1,col2 FROM indextest WHERE col1=1 AND col3=1DROP TABLE indextestThe select statement above is covered by the nonclustered index, sothat index is used. However, the nonclustered index is defined only toensure the ordering of col1 and col3 within the index; col1 and col2follow within the index as the bookmark to the clustered index. When Irun this query, my desired result is to have the records appear in theorder supported by the clustered index:1,11,2As it happens, the result I got was indeed in that order, but I don'tknow if it was mere coincidence, or if the bookmark in the nonclusteredindex is maintained in the same order as the clustered index. If Iwant to ensure the above order, is it sufficient to have thenonclustered index defined as above, or do I need to define it as:create index ix_indextest on indextest (col1,col3,col2)just to be sure that the results are returned in ascending order forcol1,col2? If the two-column index is sufficient, is it guaranteed tostill be sufficient in SQL2005 and future versions of SQL Server, or amI better off adding the third column just to be safe?Thank you,--Dennis Culley
View 4 Replies View Related
How would i find the 3rd date in a sequence of dates, that is ordered?
Example
Date1 = 08-01-01
Date2 = 08-02-01
Date3 = 08-03-01
Date4 = 08-04-01
i need to retrieve Date3
I would like to do a SELECT query and have the return set ordered by the order which the rows are physically stored in the table.
Specifically, something like:
Select a.*, b.normalizedColumn
FROM table a
JOIN table b
(a.id = b.id)
ORDER BY "Physical order of table a rows"
I believe if there is a clustered index on the table, I can just order by that index and it SHOULD be the physical order of the table.
(I would like to see this as I am generating mock data and would like to verify the "randomness" of the data inserted).
How do you all recommend storing ordered pairs in SQL Server 2005? I plan to add one record for every data point but this will generate many records and requires an extra field to relate the points together. Are there any better ways to do this? Can the data still be searchable or does it have to be unpacked first?
View 2 Replies View RelatedIve been playing with this for a few days and thought I might thow itout for seggestions.I have Several Queries that need counts returnedThe Queries are Mutually Exclusive meaning whatever Query they returnin first they cannot be included in the counts of any queries belowthem.This set of queries for exampleSelect ID From Customers where FIRST_NAME = 'Chris' (would return say150)Select ID From Customers where ST='OH' (This would retunr say 50, BUTRun alone it might return 70, however 20 of those were in the firstQuery so they arent to be retunred in this result set.The total for Bot Queries would be 200But If I reverse it like soSelect ID From Customers where ST='OH' (This now returns 70)Select ID From Customers where FIRST_NAME = 'Chris' (This now returns130)The total of course for BOT Queries is 200 but I dont need that total Ineed the total for EACH Query depending on its orderingWhat I need are the single counts depending on the order in which thequeries are runIt seems like a recursion problem, but It might go past 32 level so Icant use recursive SQL ( I dont think )I've thought of (or tried to think how to use Not In, Not Exist, etcbut still dosent come up with the results....)How Can I grab the counts for each Query ?Chris
View 5 Replies View RelatedHow can I create a function that returns hierarchical data from a table with this structure:
- CategoryID
- CategoryName
- CategoryFather
I want to bring the result set like this...
CategoryID | CategoryName | CategoryFather | HierarchicalLevel
1 | Video | 0 | 0
2 | DivX | 1 | 1
3 | WMV | 1 | 1
4 | Programming | 0 | 0
5 | Web | 4 | 1
6 | ASP.Net | 5 | 2
7 | ColdFusion | 5 | 2
How can I do this? Does anybody has a sample code? I need this on SQL Server 2000 and if it's possible (but not too necessary) in SQL Server 2005.
Thanks.
hi all,
I'm trying to get some xml data into sql server but i ran into this problem: openxml seems to repeat results ...
I simplified my example to this:
------------------------------------------------------
Declare @rDoc int,
@sDoc varchar(4000)
Set @sDoc = '
<ROOT>
<Rider>aaa</Rider>
<Rider>bbb</Rider>
<Rider>ccc</Rider>
</ROOT>'
EXEC sp_xml_preparedocument @rDoc OUTPUT, @sDoc
SELECT *
FROM OPENXML (@rDoc, 'ROOT/Rider', 1)
WITH (RiderName varchar(50) '../Rider')
----------------------------------------------------------
it returns 3 records for the 'rider' elements, _but_ all the records contain the text 'aaa' :/
does anybody know the solution to this?
cheers,
alex
Hi..I am trying to read text file using OpenRowSet function for this my DBA was created linked Server with Name "DBLServerText", my text file path c:/txtcount.txt. Please guide me syntax any one have idea.
I don't have access on XP_CMDSHELL & BULK Insert commands.
DTS package is also not allowing.
as per my knowledge, I have only one option that is OpenRowset.
Please help me the syntax using with Linked Server. with Linked it is showing the error. " You don't have OLEDB access use with Linked server"
Pls guide me
Thanks in Advance..
Mure
I have sp20, simplified, as:
ALTER PROCEDURE dbo.sp20 (@CustomerID int, @aDate as datetime) AS
SELECT Customers.* INTO #EndResult1 FROM Customers WHERE Customers.CustomerID >= @CustomerID
SELECT Orders.* INTO #EndResult2 FROM Orders Where Orders.[TakenDate] >= @aDate
SELECT #EndResult1.*, #EndResult2.*
FROM #EndResult1 INNER JOIN #EndResult2 ON #EndResult1.CustomerID = #EndResult2.CustomerID
This works fine in EM.
When I try to execute it from MS Access ADP Project I get
'Stored Procedure excuted succesfully, but did not return any records'
Although, in EM it returns the right number of records.
Thank you in advance - Rehman
I am not close to an sql server today and this question was posed to me. can someone hook me up?
" I want to query a column of values and place them into a single string seperated by commas" (as a function)
Table a
123
456
789
321
654
987
output
123,456,789,321,654,987
thanks in advance
Well, i need a piece of code that return me the schema rowset of a desicion tree and let me iterate me on it. I need some columns like node_type, node_unique_name.... etc.. And another question is that the node_distribution has multiple rows of information. How can i access them. I think there must be a adomddatareader object to iterate on them..
Well thanks a lot for your responses...
Please let me know if I am on the right track here.
I have an Execute SQL Task that selects multiple rows from an OLE DB connection, each row containing 3 columns (data types = string, Int32, Int32). In this task ResultSet = "Full result set" and Result Set > Result Name = 0, Variable Name = [User::viewInfo] which is a user variable with Data Type = Object.
I want to use a Foreach Loop Container to enumerate over the result set rows that are contained in the [User::viewInfo] variable described above. For each resultset row I want to breakout the 3 column values and assign them to 3 corresponding variables that can be referenced in a Data Flow in the Foreach Loop.
Current settings for the Foreach Loop Container: Collection > Enumerator = "Foreach ADO Enumerator", Collection > Enumerator Configuration > ADO object source variable = [User::viewInfo], Enumeration mode = "Rows in the first table". On the Variable Mappings page I select the 3 corresponding user variables I want the rowset column values assigned to, with indexes starting at 1 (not 0).
Thanks - Dana Reed
I am using a proc that runs fine in SSMS Query editor and also produces rows when I click the Preview button in the OLEDB Source Adapter. It has two input parameters. The proc contains some CTE's and UNION ALL's. It does not contain any dynamic sql. However, when I run the package I get this error:
[OLE DB Source [1]] Error: A rowset based on the SQL command was not returned by the OLE DB provider.
How can that be when the Preview shows rows being returned?
Hi,
I get the following error.
Err.Description - "Rowset does not support fetching backward."
Err. Number - -2147217884
Can somebody tell me the reason behind this error.
My Reasearch: I have got to know that I get this error in the line of code recordset.MoveLast in My code.
My Code environment: I have built an SQL Query string which calls the Strored procedure with one parameter (parameter tyoe is string type). I have attached the SP code below.
and SP contains the call for querying other database in the same server using OPENQUERY command.
and the VB code contains code as Recordset.MoveLast. (Error is generated here and Recordset.RecordCount is also -1)
SP code is:
Code Block
CREATE PROCEDURE [dbo].[sp_RMS]
@sRMS_Status CHAR(12)
AS
BEGIN
DECLARE @sSQL VARCHAR (1000)
SET @sSQL = '''SELECT *
FROM VW_JOKE
WHERE JOKE_ID = ''' + '''' + @sRMS_Status + '''' +
''' ORDER BY JOKE_NO''
EXEC ( 'SELECT * FROM OPENQUERY(lnk_joke__cat,' + @sSQL + ')' )
END
My Questions:
1). Is there any problem in SP as I am using OpenQuery? I queries the SP and concluded that it generates result properly.
2). Is there any problem with the Recordset.MoveLast line? I am using adOpenKeyset, adLockReadOnly as parameters to my Recordset.Open command along with other parameters.
Let me know the corrective steps to be taken to get rid of this error.
Thanks in Advance for your valuable time
Ranjan Jain
Hi.
In OLEDB Destination, AccessMode as OpenRowset Using FastLoad raises the following error:
"Failed to open a fastload rowset db_object. Check that the object exists in the database"
db_object exists in the database. Is there any key point for the table or view used for fastload?
Thanks
I see others having this problem when trying to run a query across a link from 2005 to a 2000 server. But we are already running SP4 on our 2000 server. What gives?
OLE DB provider "SQLNCLI" for linked server "s-1" returned message "Unspecified error".
OLE DB provider "SQLNCLI" for linked server "s-1" returned message "The stored procedure required to complete this operation could not be found on the server. Please contact your system administrator.".
Msg 7311, Level 16, State 2, Line 5
Cannot obtain the schema rowset "DBSCHEMA_TABLES_INFO" for OLE DB provider "SQLNCLI" for linked server "s-1". The provider supports the interface, but returns a failure code when it is used.
Greetings,
I have a C# application that calls a stored procedure to query the database (MSSQL 2005). I only have one field/column returned from the query but I need that column ordered.
How do I use the ORDER BY clause without returning the index column which does the sorting? The first example is NOT what I want. I want something that works like the second example which only returns the 'Name' column.
ALTER PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
SELECT DISTINCT A.Name, A.index
FROM
...
...
ORDER BY A.[Index], A.Name ASC
END
ALTER PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
SELECT DISTINCT A.Name
FROM
...
...
ORDER BY A.[Index]
END
Thanks
My goal is to have a file (it comes from another system) that I want to import via an OPENROWSET style query.
The query would look like this:
select [NoName] from openrowset('MSDASQL'
,'Driver={Microsoft Access Text Driver (*.txt, *.csv)};
DefaultDir=c:filedir'
,'select * from "file.lst"')
If I make the file a .csv it works fine. However, if it has a not CSV or TXT extension it throws the following error and cannot seem to find a solution to it.
OLE DB provider "MSDASQL" for linked server "(null)" returned message "[Microsoft][ODBC Text Driver] Cannot update. Database or object is read-only.". Msg 7350, Level 16, State 2, Line 1 Cannot get the column information from OLE DB provider "MSDASQL" for linked server "(null)".
In addition, (although I can probably find this elsewhere), I need to have the first line 'BLANK' so that it does not miss data (there is no header row). Is there a way to use OPENROWSET without BULK to basically include all rows as data?
I have a strange problem with an OleDB call to a stored procedure thatreturns a rowset.Only the first time I execute the query, after I restart SqlServer, myprogram crashes becausethe rowset is empty. All next calls (after restarting my program, ofcourse) run successfully.The context is:1) if I do not bind the output rowset, my program doesn't crash2) If I run the call without the binding and then I run the call withthe binding, it doesn't crash3) It is not the first query I do in my session4) the call crashes only if in the SP there are some inserts: it is awell known problem with OleDB, but in manyother cases I have fixed it setting NOCOUNT to ON
View 2 Replies View RelatedI am getting the following error when I execute my sql task:
An error occurred while assigning a value to variable "NullVar": " NO result rowset is associated with the execution of this query. "
I am executing a SP that has one input & one output parameter. The output parameter is returning a single row for debugging if the sp failes.
I tried using Jamie's method:(http://blogs.conchango.com/jamiethomson/archive/2005/12/09/2480.aspx) to get it to work but keep getting the above error. I have the following variables:
sqlSource (string) := Exec RBCprcsInsertWmsInvTransactionRecords '" + (DT_WSTR,10 ) @[User::SnapShotDate] + "', NULL"
NullVar (string)
In the execute sql task, I set the ResultSet to single row. I set SQLSourceType = variable & sourcevariable = user::SqlSource. In the result tab, I added a result set, NewResultName with the variable user::NullVar. I tried different configurations with the parameter mappings but nothing seemed to work. I didn't know if i still had to use this if I am using the sqlSource variable to drive the task.
So I am not sure what I am missing here. Anyone have any suggestions?
Thanks!
John
I'm trying to store the output of my stored procedure into a temp table, which takes Table Type as Input.
CREATE TYPE [dbo].[Employee] AS TABLE(
[Field] [varchar](50) NULL,
[Criteria] [varchar](50) NULL,
[Value] [varchar](50) NULL
)
declare @Employee dbo.Employee
insert into @Employee values(N'Salary',N'is greater than',N'3520')
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT * FROM OPENROWSET(''SQLNCLI'',''Server=localhost;Trusted_Connection=yes;'',''EXEC dbo.uspGetEmployee ' + @Employee + ')'
I need to create a stored procedure which uses output of the above stored procedure. Hence, I don't want to put declare and insert into OPENROWSET as I get those values as parameter to the new procedure.
Any other solution instead of using OpenRowSet.
I have a dataflow task. On which I have OLEDB as my source. I connect to my database and execute a stored proc. the stored proc results in a result set with only one row and two columns. First Column is an integer and the second row is a varchar(max) with xml script in it. Not that it should matter because it is in varchar(max).
Anyway, it give me an error
[OLE DB Source [321]] Error: A rowset based on the SQL command was not returned by the OLE DB provider.
What am I doing wrong?
Can I not have a stroed proc that returns a result set as my data source?
i have recently ported an old asp.net web application using crystal reports 9 from windows server 2003 to windows server 2008 . the crystal reports smoothly at first but one of the reports stopped working when the admin changed his password now the report is showing error. Failed to open a rowset
View 3 Replies View Relatedi got a error [OLE DB Destination [16]] Error: Failed to open a fastload rowset for "[dbo].[tempMaster]". Check that the object exists in the database.
i am creating and doping this table in beginning after insert/update i will drop this table but this is error.i am using sql server 2008R2