The following statement seems to ignore my sort expression....how can I fix this? Select TB.* FROM TblBlogs TB JOIN (select top 20 blogId, count(*) cfrom tblCommentsgroup by blogIdorder by count(*) desc) T20 ON TB.BlogId = T20.BlogId
I have a stored procedure in my SQL 2005 Server database named Foo that accepts two parameters, @paramA and @paramB.In my ASP.NET page, I have these:<asp:GridView id="gv" runat="server" AutoGenerateColumns="true" DataSourceID="DS" AllowSorting="true" DataKeyNames="ID"/><asp:SqlDataSource ID="DS" runat="server" ConnectionString="<%$ ConnectionStrings:CS1 %>" SelectCommand="Foo" SelectCommandType="StoredProcedure" OnSelecting="DS_Selecting"> <asp:Parameter Name="paramA" Type="String" /> <asp:Parameter Name="paramB" Type="String" /></asp:SqlDataSource>In my setup, paramA and paramB are set in DS_Selecting(), where I can access the Command.Parameters[] of DS.Now, here's the problem. As you can see, the GridView allows for sorting. When you click on a header title to sort, however, the GridView becomes empty. My question is, how can I get the GV sorted and in the correct direction (i.e. asc/desc)? My first step in my attempt was to add another parameter to the SqlDataSource and sotred procedure Foo (e.g. @SortByColumn), then changed Foo appropriately: ALTER PROCEDURE Foo @paramA nvarchar(64), @paramB nvarchar(64), @SortColumn nvarchar(16) = 'SearchCount' AS SELECT * FROM Searches ORDER BY CASE WHEN @SortColumn='SearchCount' THEN SearchCount WHEN @SortColumn='PartnerName' THEN PartnerName ELSE ID ENDThat works find and dandy. But wait--I want to get the correct ORDER BY direction too! So I add another parameter to the SqlDataSource and Foo (@SortDirection), then alter Foo: ... SELECT * From Searchces ORDER BY CASE /* Keep in mind that CASE short-circuits */ WHEN @SortColumn='SearchCount' AND @SortDirection='desc' SearchCount DESC WHEN @SortColumn='SearchCount' SearchCount WHEN @SortColumn='PartnerName' AND @SortDirection='desc' PartnerName DESC WHEN @SortColumn='PartnerName' PartnerName WHEN @SortColumn='ID' AND @SortDirection='desc' ID DESC ELSE ID END ...But including DESC or ASC after the column name to sort by causes SQL to error. What the heck can I do, besides convert all my stored procedures into in-line statements inside the ASP page, where I could then dynamically construct the appropriate SQL statement? I'm really at a loss on this one! Any help would be much appreciated!Am I missing a much simpler solution? I am making this too complicated?
I am using sql statement like SELECT CREATEDBY,FIRSTNAME,BUSINESS,NOTES,NOTESDATE FROM BUSINESS ORDER BY NOTESDATE DESC, CREATEDBY ASC But NotesDate is sorting descending order, but only sorting based on the date and month not on year Please help me
I have state, day_date, error, and text column. If there is data then it is showing all the columns. But if there is no comments I would like to show no comments in the text field. Currently I have this store procedure.
CREATE PROCEDURE dbo.up_daily_quad_text
@DAY_DATE datetime
AS
BEGIN
SELECT
dbo.adins_database.ZONE_NAME + ', ' + dbo.adins_database.ZONE_STATE AS [STATE AND LOCATION],
dbo.COMMENT_CATEGORY.NAME,
dbo.COMMENT.TEXT
FROM
dbo.adins_database,
dbo.COMMENT_CATEGORY,
dbo.COMMENT,
dbo.DIM_DATE
WHERE
( dbo.adins_database.adins_id=dbo.COMMENT.adinsdb_id OR (dbo.COMMENT.adinsdb_id is Null) )
AND ( dbo.COMMENT.comment_dt=dbo.DIM_DATE.DAY_DATE )
AND ( dbo.COMMENT_CATEGORY.category_id=dbo.COMMENT.category_id )
AND
dbo.DIM_DATE.DAY_DATE = @DAY_DATE
END
GO
GRANT EXECUTE ON dbo.up_daily_quad_text TO AdIns_SSRS
I've broken down and started one of these things: http://blogs.msdn.com/ryan.stonecipher/default.aspx . Watch that space for "good to know about DBCC" stuff.
Thanks,
---------------------- Ryan Stonecipher Developer, Microsoft SQL Server Storage Engine, DBCC (Legalese: This posting is provided "AS IS" with no warranties, and confers no rights.)
I'm creating a temporary table in a Sql 2005 stored procedure that contains the transaction amount entered in a period <= the period the user enters. I can return that amount in my result set. But I also need to separate out by account the amounts just in the period = the period the user enters. There can be many entries or no entries in any period. I populate the temporary table this way:
SELECT t.gl7accountsid, a.accountnumber, a.description, a.category, t.POSTDATE, t.poststatus, t.TRANSACTIONTYPE, t.AMOUNT, case when t.transactiontype=2 then amount * (-1) else amount end as transamount, t.ENCUMBRANCESTATUS, t.gl7fiscalperiodsid
FROM UrsinusCollege.dbo.gl7accounts a
join ursinuscollege.dbo.gl7transactions t on a.gl7accountsid=t.gl7accountsid
where (t.gl7fiscalperiodsid >= 97 And t.gl7fiscalperiodsid<=@FiscalPeriod_identifier) And poststatus in (2,3) and left(a.accountnumber,5) between '2-110' and '2-999' And right(a.accountnumber,4) > 7149 And not(right(a.accountnumber,4)) in ('7171','7897')
order by a.accountnumber
Later I create a temporary table that contains budget information. I join these 2 temporary tables to produce my result set. But I don't know how to get the information for just one period. For example, if the user enters 99 as the FiscalPeriod_identifier, I need a separate field that contains only those amounts(if any) that were entered for each account in Period 99.
Can anyone help? It may be that I am not seeing the forest for the trees, but I can't figure it out.
Hello,I am creating a simple blog system using SQL 2005.I have a Blog table:[BlogId] > PostId (PK), BlogTitle, ...And a Posts table[Posts] > PostId (PK), BlogId (FK), PostContent, PostLabels, ...PostLabels would have the following format:Label1,Label2,Label3, etc ...I will need to perform 3 actions:1. Get all posts in blog2. Get all labels in a post3. Get all unique existing labels in all posts in a blog and make a list.I am not sure if my approach of using a simple labels column in my Posts table is a good idea.So my other idea would be to add two more tables:[BlogLabels] > BlogLabelId (PK), BlogId (FK), LabelName ...[LabelsInPosts] > BlogLabelId (PK), PostId (PK)So my idea is:1. When creating a post one of the parameters would be a comma separating string with all labels for the post. Inside SQL Procedure I will need to loop through each label and check if it exists in BlogLabels. If not then I added it. For each label I add a records in LabelsInPosts. How to create this loop? Am I thinking this right?2. To get a list of all labels in a blog I would need to go to BlogLabels and get all labels which are related with posts in LabelsInPosts. Those posts must be only the ones that are related with my given BlogId. Grrr, this is getting really confusing for me. Is this possible to to? How?Please, give me some advice about all this.Thanks,Miguel
I have a report where I am giving the users a parameter so that they can select which field they would like to sort on.The report is also grouping by that field. I have a gruping section, where i have added code to group on the field I want based on this parameter, however I also would like to changing the sorting order but I checked around and I did not find any info.
So here is my example. I am showing sales order info.The user can sort and group by SalesPerson or Customer. Right now, I have code on my dataset to sort by SalesPerson Code and Order No.So far the grouping workds, however the sorting does not.
SSRS 2012 - VS2010...The report compares two years with a sort order on a value that has been engineered based on text switched to int. When sorting A-Z this is the result in the horizontal axis is: 5th, K, 1st, 2nd, 3rd, 4th, 5th..When sorting Z-A the result in the horizontal axis is:5th, 4th, 3rd, 2nd, 1st, PreK..Z-A is correct but A-Z sorting shows 5th as the start and end. The magnitude of the PreK location is correct but the label is wrong on the A-Z sort order. The sorting is implemented using the Category Group sorting option.
I have a simple blog with a posts and replies table.
on the posts summary page i want to count the number of replies related to each post.
I thought i could store all the posts in a table variable and then loop through the table variable to count the number of replies that relate to the current post.
It doesnt seem as easy as i expected and i think i am making it more complicated for myself.
Can someone point me in the right direction please ?
I've never worked with a column that's defined as a binary data type. (In the past if ever we had to include a photo we stored a link to the JPG/BMP/PNG/whatever into a column, but never actually inserted or updated a column with binary data.But now I've got to do that. So how do you put data into a column defined as BINARY(4096)?
I have a table named Prescription that consists of attributes like PatientId, MedicineCode, MedicineName, Prices of different drugs, quantity of different drugs(e.g 1,2,3,10), date .
I would like to get a summary of the total number and amount of different drugs in a specific period, the total amount of each type of drug.
Hi. I am currently building a blog application, and I need some advice... I have the post title, post date, post by, etc stored in a database table, however I was wondering whether I should store the actual post content in the database as well or in a text file. For example, if the posts get really long would it slow down database performance or would there not be much of a difference? Furthermore, if I wanted to keep the posts private, a text file would not be ideal as it can be accessed easily by surfers... What do you recommend?Thanks a lot
insert into Channels values (1, 'Channel 1'); insert into Channels values (2, 'Channel 2'); insert into Channels values (3, 'Channel 3'); insert into Channels values (4, 'Channel 4');
insert into Blogs values ('1', 'blah'); insert into Blogs values ('3', 'blah'); insert into Blogs values ('4', 'blah'); insert into Blogs values ('12', 'blah'); insert into Blogs values ('34', 'blah'); insert into Blogs values ('35', 'blah'); insert into Blogs values ('67', 'blah');
insert into Episodes values (1, 3, '', '', 'Episode 1, blog 3'); insert into Episodes values (2, 3, '', '', 'Episode 2, blog 3'); insert into Episodes values (3, 3, '', '', 'Episode 3, blog 3'); insert into Episodes values (4, 3, '', '', 'Episode 4, blog 3'); insert into Episodes values (5, 1, '', '', 'Episode 5, blog 1'); insert into Episodes values (6, 1, '', '', 'Episode 6, blog 1'); insert into Episodes values (7, 1, '', '', 'Episode 7, blog 1'); insert into Episodes values (8, 4, '', '', 'Episode 8, blog 4'); insert into Episodes values (9, 4, '', '', 'Episode 9, blog 4'); insert into Episodes values (10, 4, '', '', 'Episode 10, blog 4'); insert into Episodes values (11, 4, '', '', 'Episode 11, blog 4'); insert into Episodes values (12, 4, '', '', 'Episode 12, blog 4'); insert into Episodes values (13, 12, '', '', 'Episode 13, blog 12'); insert into Episodes values (14, 12, '', '', 'Episode 14, blog 12'); insert into Episodes values (15, 12, '', '', 'Episode 15, blog 12'); insert into Episodes values (16, 12, '', '', 'Episode 16, blog 12'); insert into Episodes values (17, 12, '', '', 'Episode 17, blog 12'); insert into Episodes values (18, 34, '', '', 'Episode 18, blog 34'); insert into Episodes values (19, 34, '', '', 'Episode 19, blog 34'); insert into Episodes values (20, 34, '', '', 'Episode 20, blog 34'); insert into Episodes values (21, 34, '', '', 'Episode 21, blog 34'); insert into Episodes values (22, 35, '', '', 'Episode 22, blog 35'); insert into Episodes values (23, 35, '', '', 'Episode 23, blog 35'); insert into Episodes values (24, 35, '', '', 'Episode 24, blog 35'); insert into Episodes values (25, 35, '', '', 'Episode 25, blog 35'); insert into Episodes values (26, 67, '', '', 'Episode 26, blog 67'); insert into Episodes values (27, 67, '', '', 'Episode 27, blog 67'); insert into Episodes values (28, 67, '', '', 'Episode 28, blog 67'); insert into Episodes values (29, 67, '', '', 'Episode 29, blog 67'); insert into Episodes values (30, 67, '', '', 'Episode 30, blog 67');
insert into BlogAssociations values (3,'',1); insert into BlogAssociations values (12,'',1);
There is my above sql script, i'm currently using mysql at home to test things but will convert to work in mssql. I need to get associated BlogID for Certain ChannelID from the BlogAssociations table. Then using those BlogID's that it finds for let just say ChannelID "1" list off the 3 most recent EpisodeID's from the Episodes Table per each BlogID. So if ChannelID "1" has four BlogID's associated with it then in the Episodes table list off the recent 3 EpisodeIDs for BlogID "3", then the 3 most recent EpisodeIDs for BlogID "5" and so on and so on.
I have this which kind of does what I want:
Code:
select e.BlogID, e.EpisodeID, e.other FROM episodes e, BlogAssociations ba WHERE e.BlogID = ba.BlogID and ba.ChannelID = '1' ORDER BY e.EpisodeID DESC;
It returns:
Code:
+--------+-----------+---------------------+ | BlogID | EpisodeID | other | +--------+-----------+---------------------+ | 12 | 17 | Episode 17, blog 12 | | 12 | 16 | Episode 16, blog 12 | | 12 | 15 | Episode 15, blog 12 | | 12 | 14 | Episode 14, blog 12 | | 12 | 13 | Episode 13, blog 12 | | 3 | 4 | Episode 4, blog 3 | | 3 | 3 | Episode 3, blog 3 | | 3 | 2 | Episode 2, blog 3 | | 3 | 1 | Episode 1, blog 3 | +--------+-----------+---------------------+
But as you can see it lists off 5 of the Episodes for BlogID "12", I only want the most recent 3 as previously stated. It also lists off more than 3 Episodes for BlogID "3". How in the world do I go about doing this? I'm making this a stored procedure so I can't use php otherwise I wouldn't even be posting
Hey guys, I have a view with dates (TheDate) meant to be arranged in descending order. When I 'Execute SQL' while in the view, the DESC order works just fine and shows up with the latest date first going down. However, once I 'OPEN VIEW' the order keeps defaulting to ASCending order.
How do I keep it in DESC order for viewing? Here's the statement:
SELECT TOP (100) PERCENT TheDate FROM dbo.MyDates ORDER BY TheDate DESC
In the followinf portion of my SQL Statement, I cannot figure out how to specify ASC or DESC for the OrderBy... If I Put OrderDate ASC after the THEN, I get an error and if I put @SortDir after the END I get an error... Can Anyone help with this? WHERE OrderID IN(SELECT OrderID FROM #rsltTable WHERE ID >= @l_FirstRecord AND ID <= @l_LastRecord)ORDER BYCASE @OrderByWHEN 'OrderDate ASC' THEN OrderDateWHEN 'OrderDate DESC' THEN OrderDateEND Thank You,Jason
hi, i have headers at the top of my list and would like for people to click the pubs link and it orders the pubs alphabetically descending and when they click again to ascend also to do this with towns and addresses and postcodes?!
Does anyone have a general rule or guide on when to use this SQL 2000 option when creating indexes? I was thinking generally on nonclustered indexes where the column would be unique and incremental and usually filtered on by range and often used in the order by clause. Such as columns of datetime or integers datatypes. Thanks.
I have a column name "DESC" in SQL Server table and I am getting an error when trying to insert data into this column. I cannot rename this column as it's not in my hand.
Please anybody reply me with good solution I am new to SQL.
Hi, I have been training in SQL on MySQL, and now that I am on TSQL, I can't seem to find an equivalent to the command:
Code Snippet
DESC table_name;--OR DESCRIBE table_name;
In MySQL, either command returns a list of the columns of the table, as well specifications about these columns (whether or not they can accept NULL values, their default values, etc.)
There is a index: CustomerInfo_1 with keys: customerId, EnteryDate DESC I could not find where the order of index key (i.e. whether the key is ascending or descending) is stored? I tried system tables such as sysindexes and sysindexkeys tables. But could not find it. Any help in this regard will be truly appreciated.
There is a index: CustomerInfo_1 with keys: customerId, EnteryDate DESC I could not find where the order of index key (i.e. whether the key is ascending or descending) is stored? I tried system tables such as sysindexes and sysindexkeys tables. But could not find it. Any help in this regard will be truly appreciated.
Hi all,I have a SQL statement that allows paging and dynamic sorting of thecolumns, but what I can't figure out without making the SQL a dynamicstring and executing it, or duplicating the SQL statement between anIF and ELSE statement.Following is the SQL statement;set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgoALTER PROCEDURE [dbo].[sp_search]@search VARCHAR( 80 ), @startRow INT = 1, @endRow INT = NULL, @postcode AS CHAR( 4 ) = NULL, @suburb AS VARCHAR( 40 ) = NULL, @stateIdentity AS TINYINT = NULL, @fromLatitude AS REAL = NULL -- latitude the user is located in, @fromLongitude AS REAL = NULL -- longitude the user is located in, @sort TINYINT = 1ASBEGINSET NOCOUNT ON;DECLARE @calculateDistance BIT;SET @calculateDistance = 0;-- get the longitude and latitude if requiredIF ( NOT @postcode IS NULL )BEGINSELECTDISTINCT@fromLatitude = latitude, @fromLongitude = longitudeFROMtbl_postalcodeWHERE(postalcode = @postcode)SET @calculateDistance = 1ENDELSE IF ( NOT @suburb IS NULL AND NOT @stateIdentity IS NULL )BEGINSELECTDISTINCT@fromLatitude = latitude, @fromLongitude = longitudeFROMtbl_localityWHERE(locality = @suburb)AND(stateIdentity = @stateIdentity)SET @calculateDistance = 1END/*ELSE IF ( @fromLatitude IS NULL AND @fromLongitude IS NULL )BEGINRAISERROR( 'You need to pass a valid combination to this storedprocedure, example: postcode or suburb and state identity or longitudeand latitude', 18, 1 );END*/SELECT D1.[row], D1.[totalRecordCount], D1.[classifiedIdentity], D1.[title], D1.[summary], D1.[price], D1.[locality], D1.[state], D1.[postcode], D1.[addedLast24], D1.[dateStamp], D1.[t2Rank], D1.[t3Rank], D1.[tRank], D1.[distance], F.[originalName], F.[extension], F.[uniqueName]FROM(-- derived tableSELECT ROW_NUMBER() OVER ( ORDER BY CASE @sort WHEN 0 THENCAST( COALESCE( t2.RANK, 0 ) + COALESCE( t3.RANK, 0 ) AS CHAR( 5 ) )WHEN 1 THEN C.title WHEN 2 THEN CAST( CEILING( [dbo].[fn_calculateDistance] ( @fromLatitude, @fromLongitude, L.latitude,L.longitude ) ) AS CHAR( 9 ) ) WHEN 3 THEN ( C.locality + ' ' +C.state ) WHEN 4 THEN CAST( C.price AS CHAR( 10 ) ) END ASC ) AS row, COUNT( * ) OVER() AS totalRecordCount, C.[classifiedIdentity], C.[title], C.[summary], C.[price], C.[locality], C.[state], C.[postcode], CASE WHEN ( C.[dateStamp] >= DATEADD( day, -1, GETDATE() ) )THEN 1 ELSE 0 END AS addedLast24, C.[dateStamp]/* , t1.RANK AS t1Rank */, t2.RANK AS t2Rank, t3.RANK AS t3Rank, /* COALESCE( t1.RANK, 0 ) + */ COALESCE( t2.RANK, 0 ) +COALESCE( t3.RANK, 0 ) AS tRank, CASE @calculateDistance WHEN 1 THEN CEILING( [dbo].[fn_calculateDistance] ( @fromLatitude, @fromLongitude, L.latitude,L.longitude ) ) ELSE 0 END AS distanceFROM [tbl_classified] AS CINNER JOINtbl_locality LONC.localityIdentity = L.localityIdentity/* LEFT OUTER JOINCONTAINSTABLE( tbl_category, title, @keyword ) ASt1ON FT_TBL.categoryIdentity = t1.[KEY] */LEFT OUTER JOINCONTAINSTABLE( tbl_classified, title, @search ) ASt2ON C.classifiedIdentity = t2.[KEY]LEFT OUTER JOINCONTAINSTABLE( tbl_classified, description,@search ) AS t3ON C.classifiedIdentity = t3.[KEY]WHERE ( /* COALESCE( t1.RANK, 0 ) + */COALESCE( t2.RANK, 0 ) +COALESCE( t3.RANK, 0 ) ) != 0) AS D1LEFT OUTER JOINtbl_classified_file CFOND1.classifiedIdentity = CF.classifiedIdentityLEFT OUTER JOINtbl_file FONF.fileIdentity = CF.fileIdentityWHERE( row >= @startRow )AND( @endRow IS NULL OR row <= @endRow )ENDThe part I'm having trouble with is making the sort order in thefollowing line dynamicORDER BY CASE @sort WHEN 0 THEN CAST( COALESCE( t2.RANK, 0 ) +COALESCE( t3.RANK, 0 ) AS CHAR( 5 ) ) WHEN 1 THEN C.title WHEN 2 THENCAST( CEILING( [dbo].[fn_calculateDistance] ( @fromLatitude,@fromLongitude, L.latitude, L.longitude ) ) AS CHAR( 9 ) ) WHEN 3 THEN( C.locality + ' ' + C.state ) WHEN 4 THEN CAST( C.price ASCHAR( 10 ) ) END ASCany help would be greatly apprecaited.Thanks
I have come across a problem executing a select with a multi-part where clause that only shows up if there are multiple indexes on the table. The situation using a simplified table is shown below
create table tblTest( utcTimestamp datetime NOT NULL, testType int NOT NULL)go
insert into tblTest (utcTimestamp, testType) VALUES('6/1/2003 0:0:0', 100)go
Now, without adding any indexes to the table, I can execute the following select and it works fine, returning the single row in 2003:
select * from tblTest where utcTimestamp < '1/1/2004 0:0:0' and utcTimestamp > '1/1/2003 0:0:0' and testType = 100go
Furthermore, if I introduce a single descending index on just the utcTimestamp:
CREATE INDEX IX_tblTest_Timestamp ON tblTest (utcTimestamp DESC)go
the search still works.
HOWEVER, if I now introduce another index:
CREATE INDEX IX_tblTest_EntryType_Timestamp ON tblTest ( testType, utcTimestamp DESC)go
the search does **not** return the row. However, if I change the where clause to remove the test of testType:
select * from tblTest where utcTimestamp < '1/1/2004 0:0:0' and utcTimestamp > '1/1/2003 0:0:0'go
it works.
Also, strangely, if I populate the table with a number of records with different dates and execute the following search:
select * from tblTest where utcTimestamp > '1/1/2004 0:0:0' and testType = 100go
I get records from **earlier** than 1/1/2004 (i.e. like the sense of the compare is wrong)
Finally, as I was writing this report, I discovered that all of these problems go away if the DESC is removed from the indexes - so that's my workaround, but it still looks like a bug.
Identity(1,1) column ID is primary key and only clustered index key.
Rows will be inserted regularly into this table, hundreds per day.
Queries will be mostly selecting on the most recent records.
In a year, the row will have half a million records or so and only the most recent records will be used. There will be a forward-rolling hot spot, of most recent records.
Does the direction of the ID column in the clustered index make a difference?
I'm thinking no, because query plan will go to that leaf in an index seek regardless of whether it is old or new, "bottom" or "top" of index, especially if the query is very specific on the ID.
I am trying to order by the field and direction as provided by input parameters @COLTOSORTBY and @DIR while using a CTE and assigning Row_Number, but am running into syntax errors.
Say I have a table called myTable with columns col1,col2,col3,
Here's what I'm trying to do
with myCTE AS ( Select col1 ,col2 ,col3 ,row_number() over (order by case when(@DIR = 'ASC') then
case when @COLTOSORTBY='col1' then col1 asc when @COLTOSORTBY='col2' then col2 asc else col3 asc end else
case when @COLTOSORTBY='col1' then col1 desc when @COLTOSORTBY='col2' then col2 desc else col3 desc end end from myTable )
Please let me know what i can do with minimal code repetition and achive my goal of dynamically sorting column and direction. I do not want to use dynamic SQL under any circumstance.