I need to run a query on Mysql DB that retrieve the last 10 rows from a table which have no index column. I succeed to create the query-
SET #row_number:=0;
select activity from (
SELECT #row_number:= #row_number+ 1 AS rowNumber, activity
FROM activities a ) as myT
where myT.rowNumber > (select count(activity) from activities)- 10
But i need to run it through C#. And using MysqlCommand i can't create the parameter #row_number. Using command.Parameters.AddWithValue dosen't help
because the parameter need to be assigned when the query is executing.
(using the Parameters.AddWithValue produce the following error =
"..syntax to use near ':= 1 + 1...").
Thanks.
I think what you want is the LIMIT clause:
select activity from activities
LIMIT 10
I believe you'll have to create a stored procedure if you want to use a parameter for the LIMIT amount.
Maybe I'm misunderstanding your question but if you're only trying to grab the first 10 records why not use this:
SELECT TOP 10 [columnName] FROM [Table]
This returns the top 10 results in the database table.
or in C# you can set a variable
int rowNumber = 0;
then use the command.Parameter.add("#rowNumber", rowNumber);
that might work.
Hope this helps.
Related
I have to remove the particular value from the sentence which is stored in SQL database. Sentence will look like this:
1 Payments:ihj - CHENNAI-HIRE:54005-TN69AZ54008,4021-TN69AZ54005
2 Payments:ihj - CHENNAI-HIRE:54004-TN69AZ54008,4021-TN69AZ54005,54005-TN69AZ54008
In above sentence 54004 is the number which I will pass as parameter to SQL. This is the number which I want to remove from this line but same number is present in this line as TN69AZ54005. This number should not be disturbed, and in another payment we have same amount in another place. Can anyone help on this?
I tried with this sql query
declare #text int=4019
select SUBSTRING(notes,CHARINDEX(cast(#text as varchar),notes),
len(notes)-CHARINDEX(',',notes)+1)
from Accounts.TransactionNotes
where TransactionID=1978
If I use this query it will affect including this line TN69AZ54005
I can see that you've included a C# tag into your question. Then probably the easiest way is just to select all necessary rows using your app, then iterate through them and change the strings to your needs (using eg. PHP preg_replace() equivalent) and update the SQL rows.
I believe that is the easiest way, not really SQL solution but still...
update <table> set notes = replace(notes, 'HIRE:'+ str(<inputparam>),'HIRE:') where transactionid=<transactionid>
update <table> set notes = replace(notes, ','+ str(<inputparam>),',') where transactionid=<transactionid>
You will need to find something to prefix your inputpram value, like in above example I am using "HIRE:" or a comma.
Another way could be to use REGEXP to find the whole word, then one one query would suffice. But I haven't tried it.
The problem here is not the query but the person who designed the
database.
I`m not sure is it this what you want but I will past my code. :)
-- for test create #temp
SELECT
A.DATA
INTO #Temp
FROM
(
SELECT 'Payments:ihj - CHENNAI-HIRE:54005-TN69AZ54008,4021-TN69AZ54005' AS DATA
UNION
SELECT 'Payments:ihj - CHENNAI-HIRE:54004-TN69AZ54008,4021-TN69AZ54005,54005-TN69AZ54008' AS DATA
) AS A
GO
-- this you want?
UPDATE #Temp
SET DATA = REPLACE(DATA,'54004','')
GO
-- select changed data
SELECT * FROM #Temp
I have a problem with an SQL query.
I use Visual Studio 2015 to test my website, and WebMatrix.Data.Database to do my queries.
Anyways, I am creating a reply system and I use this query to get the replies :
SELECT *
FROM ThreadReply
WHERE ThreadId = " + ThreadId + "
ORDER BY ReplyId DESC
I know there is no prevention against SQL injections so please don't ask me to fix that.
Want I want to add the the query is to start from a certain row and continue for a certain amount of rows, for example; I mean like the LIMIT command where you can select the rows you want to start at but apparently it doesn't work on Visual Studio.
Also, please note, I want the row from the query with the rows that have the WHERE keyword true, so not the row of the actual table.
Here you go, the comments of the sql are pretty clear I think. Also I fix your sql injection, you just need to add the SqlCommand.Parameters
SELECT
*
FROM
ThreadReply
WHERE
ThreadId=#ThreadID
ORDER BY
ReplyId DESC
OFFSET
10 ROWS -- skip 10 rows
FETCH NEXT
10 ROWS ONLY -- take 10 rows
Im using Data Adapter/Set in SQL CE, i do create the following query to insert into table and then SELECT ##IDENTITY,
I want this SELECT statement return me the Student ID each time after Inserting into table, here is my Query:
INSERT INTO [Student] ([Name], [Family], [Address], [Phonenumber])
VALUES(#Name,#Family,#Address,#Phonenumber);
SELECT ##IDENTITY;
here is how i call query:
int x = da.Insert("Albert", "Alexandra", "No4.Oxford", Telnum);
Int x suppose to return me ID...
Here is the Error im getting :
There was an error parsing the query. [ Token line number = 4,Token line offset = 1,Token in error = SELECT ]
Insert Query it self it works but once adding SELECT ## IDENTITY at the end im getting error.
I really don't know what i'm doing wrong.
The return value of ExecuteNonQuery will be number of rows effected by these query. so you need to use store procedure instead of Single Query.
According to MSDN, CE doesn't support multiple commands per execution and you need to do this as two commands synchronously.
If you'd like to do this in a single call, you need to use a stored procedure rather than Insert, because it uses ExecuteNonQuery, which does not return any records. Otherwise you'll need to perform a select in another call to determine the identity.
The return value of ExecuteNonQuery is an integer that denotes the number of rows affected by your call.
I'm running a query that retrieves 20 rows (for example). I want to know if there are 21 so I can enable the 'next page' button accordingly. At the moment I'm retrieving pageSize + 1 and returning a boolean as an out parameter which is assigned it's value based on whether there were 21 (in this case) rows retrieved but will only actually return the 20 as a List. This means I'm retrieving an extra one though which I then just disregard which isn't ideal for performance and I don't want to run a count(*) because it's another query altogether.
NOTE: Using a pageddatasource isn't really an option, got to stick with rowlimit's and start rows.
Thanks for any suggestions.
You can use a nested query, something like this:
select TOP 20 *,
(select count(*) from tableName) as TotalCount
from tableName
Then each row will have the total column, so you can check that.
Alternatively, you could use this syntax, avoiding the nested select. This will become more convenient when you have additional predicates (which don't have to be repeated in the nested select):
select TOP 20 *, count(*) over() as TotalCount
from tableName
2 queries:
the page of results
then total number of results
the first query will contain the page and page size, the second will provide you with the total number of rows. With this information you can calculate the total number of pages and present this to the user.
I would doubt that retrieving one extra row (21 vs 20) within the same DB access is anything but negligible in terms of performance.
Get the count(*) for one time. Use it to display the number of pages.
Each time user clicks page number, get the 20 records
Try this
Select *,Row_Number .... as RowNo
into #Table
from Table
Select *
from #Table
WHERE RowNo > #FirstRec AND RowNo < #LastRec
Select count(*)
from #Table
Here's one that uses row_number
–-Change these two variable to parameters of your
–-actual stored procedure
Declare #PageNumber int
Declare #PageSize int
–-Assume we need page 6 i.e. records from 51-60
Select #PageNumber=6
Select #PageSize=10
–-Select only those records which
–-fit into a single page
Select Top(#PageSize) * from
(
Select
RowID=ROW_NUMBER() OVER (ORDER BY Name),
ProductID,Name,ProductNumber,ListPrice,
TotalRows=Count(*) OVER() --Count all records
from Production.Product
) A
Where A.RowId > ((#PageNumber-1)*#PageSize)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
SQL Server Random Sort
I guess it sounds stupid but I want to retrieve a few records randomly each time user refreshes the page. is there any Query available for SQL Server 2005 to do that or should I do this in page?
Try this:
SELECT TOP 10 Field1, ..., FieldN FROM Table1 ORDER BY NEWID()
NEWID() creates a unique value of uniqueidentifier type. Take a look at this.
Hope it helps.
Yes, there is
I don't know about SQL Server but seeing as SQL is meant to be standardised, you could try the MySQL way: As far as I can remember you just have to use a MySQL function, rand() to sort your SELECT call and then limit the length to 1, so as to get only the first result.
SELECT * FROM tableName ORDER BY rand() LIMIT 1
Give that a go, hope it helps!