Wednesday, March 28, 2012
Numbering each row in my resultset
Example: select <...>, state from tbl_states (<...> is what I am asking for)
Col1 Col2
1 Ohio
2 New York
3 California
4 Texas
I have seen some solutions using count(*), group by and joins to achieve
this. However I have images that I retrieve in columns 2 (instead of the
states) and group by is not compliant with image datatype.
I think Oracle has something called rownum that does what I want, but I
don't know how to do this with SQL Server.
Anybody knows?
Why not add the row number client-side? That can work out much more
efficient than any of the potential SQL solutions. Here's one SQL
alternative:
SELECT
(SELECT COUNT(*)
FROM YourTable
WHERE key_col <= T.key_col) AS col1,
col2
FROM YourTable AS T
David Portas
SQL Server MVP
|||Why make the query treat each row individually? The client has to do that
anyway, so it is a much more appropriate place to keep a running count.
http://www.aspfaq.com/
(Reverse address to reply.)
"Billy" <Billy@.discussions.microsoft.com> wrote in message
news:D2BEB8E4-C710-4027-A1EF-1D8166A6DB10@.microsoft.com...
> In my query I want to succesively number each record I retrieve from a
table.
> Example: select <...>, state from tbl_states (<...> is what I am asking
for)
> Col1 Col2
> --
> 1 Ohio
> 2 New York
> 3 California
> 4 Texas
> I have seen some solutions using count(*), group by and joins to achieve
> this. However I have images that I retrieve in columns 2 (instead of the
> states) and group by is not compliant with image datatype.
> I think Oracle has something called rownum that does what I want, but I
> don't know how to do this with SQL Server.
> Anybody knows?
>
Monday, March 26, 2012
Numbering each row in my resultset
Example: select <...>, state from tbl_states (<...> is what I am asking for)
Col1 Col2
--
1 Ohio
2 New York
3 California
4 Texas
I have seen some solutions using count(*), group by and joins to achieve
this. However I have images that I retrieve in columns 2 (instead of the
states) and group by is not compliant with image datatype.
I think Oracle has something called rownum that does what I want, but I
don't know how to do this with SQL Server.
Anybody knows?Why not add the row number client-side? That can work out much more
efficient than any of the potential SQL solutions. Here's one SQL
alternative:
SELECT
(SELECT COUNT(*)
FROM YourTable
WHERE key_col <= T.key_col) AS col1,
col2
FROM YourTable AS T
--
David Portas
SQL Server MVP
--|||Why make the query treat each row individually? The client has to do that
anyway, so it is a much more appropriate place to keep a running count.
--
http://www.aspfaq.com/
(Reverse address to reply.)
"Billy" <Billy@.discussions.microsoft.com> wrote in message
news:D2BEB8E4-C710-4027-A1EF-1D8166A6DB10@.microsoft.com...
> In my query I want to succesively number each record I retrieve from a
table.
> Example: select <...>, state from tbl_states (<...> is what I am asking
for)
> Col1 Col2
> --
> 1 Ohio
> 2 New York
> 3 California
> 4 Texas
> I have seen some solutions using count(*), group by and joins to achieve
> this. However I have images that I retrieve in columns 2 (instead of the
> states) and group by is not compliant with image datatype.
> I think Oracle has something called rownum that does what I want, but I
> don't know how to do this with SQL Server.
> Anybody knows?
>
Numbering each row in my resultset
.
Example: select <...>, state from tbl_states (<...> is what I am asking for
)
Col1 Col2
--
1 Ohio
2 New York
3 California
4 Texas
I have seen some solutions using count(*), group by and joins to achieve
this. However I have images that I retrieve in columns 2 (instead of the
states) and group by is not compliant with image datatype.
I think Oracle has something called rownum that does what I want, but I
don't know how to do this with SQL Server.
Anybody knows?Why not add the row number client-side? That can work out much more
efficient than any of the potential SQL solutions. Here's one SQL
alternative:
SELECT
(SELECT COUNT(*)
FROM YourTable
WHERE key_col <= T.key_col) AS col1,
col2
FROM YourTable AS T
David Portas
SQL Server MVP
--|||Why make the query treat each row individually? The client has to do that
anyway, so it is a much more appropriate place to keep a running count.
http://www.aspfaq.com/
(Reverse address to reply.)
"Billy" <Billy@.discussions.microsoft.com> wrote in message
news:D2BEB8E4-C710-4027-A1EF-1D8166A6DB10@.microsoft.com...
> In my query I want to succesively number each record I retrieve from a
table.
> Example: select <...>, state from tbl_states (<...> is what I am asking
for)
> Col1 Col2
> --
> 1 Ohio
> 2 New York
> 3 California
> 4 Texas
> I have seen some solutions using count(*), group by and joins to achieve
> this. However I have images that I retrieve in columns 2 (instead of the
> states) and group by is not compliant with image datatype.
> I think Oracle has something called rownum that does what I want, but I
> don't know how to do this with SQL Server.
> Anybody knows?
>
Wednesday, March 21, 2012
Number of duplicate record
same content.
For example, this is my database (Data1 only has 1 column)
Table Data1
Column numbers
234
322
2323
234
453
234
412
2323
the query should like something like this
Select ..... From Data1 Where ... numbers =..
if i use
Select ..... From Data1 Where ... numbers = 234
it would return 3, because there are 3 234s in the column
Thanks in Advance,
AaronHi Aaron,
You could try
Select count(*) from Data1 Where Numbers = 234
HTH
Barry|||Select count(*) From Data1 Where numbers = 234
"Aaron" <kuya789@.yahoo.com> wrote in message
news:%23$tXt9cHFHA.1392@.TK2MSFTNGP10.phx.gbl...
> I need help writing a query that can tell me the number of records with
the
> same content.
> For example, this is my database (Data1 only has 1 column)
> Table Data1
> Column numbers
> 234
> 322
> 2323
> 234
> 453
> 234
> 412
> 2323
> --
> the query should like something like this
> Select ..... From Data1 Where ... numbers =..
> if i use
> Select ..... From Data1 Where ... numbers = 234
> it would return 3, because there are 3 234s in the column
>
> Thanks in Advance,
> Aaron
>|||Aaron,
If you want count the duplicate Records for the whole table rather than
individually then use:
select count(*), Numbers
>From Data1
Group By Numbers
Having Count(Numbers) > 1
HTH
Barry|||thanks.
"Barry" <barry.oconnor@.singers.co.im> wrote in message
news:1109683340.054164.176760@.g14g2000cwa.googlegroups.com...
> Aaron,
> If you want count the duplicate Records for the whole table rather than
> individually then use:
> select count(*), Numbers
> Group By Numbers
> Having Count(Numbers) > 1
> HTH
> Barry
>
Tuesday, March 20, 2012
number of affected records
Okay..i have this problem ...i am using SQL server 2005 standard ,C#,VS2005
--i am inserting some record in DB .. using ExecuteNonQuery...i want to know how many records are getting inserted..so in my DB class i did something like this : numRecords = commandObject.ExecuteNonQuery() ,assuming that ExecuteNonQuery returns the number of affected records.i am retriving this numOfRecords in my code behind and printing it but it always prints 1,even though more then one records are inserted.What is wrong here?
-i also have returnValue defiend like this.Could this tell me anything about how many records are inserted or affected during update,select ?if so,how?
cmd.Parameters.Add(newSqlParameter("@.returnVal",SqlDbType.Int));
cmd.Parameters["@.returnVal"].Direction =ParameterDirection.ReturnValue;
Please help me out with this.Thanks
Are you positive your INSERT statement isn't inserting records 1 at a time, like in a loop or something to that effect? Can you post your query?You can retrieve values back using the method you wrote above.|||
oh...now that you pointed out...yes..my insert is inserting 1 record at a time in a loop...i am inserting it using the stored procedure...but i want to know how many got inserted at the end of looping successfully...in fact i know 'how many part' as well..b/c my dropdownList gets updated instantly with the inserted values,so i can look at it<but i don't want to rely on that to decipher out the num of recs>.Instead i wanted to display the num of recs affected ,as soon as i click on 'add' button,some parameters-something which comes out from DB as a result of executing of query.Do u think thats possible?or do i have to check on successful returnValue in a loop and increment the counter,to tell me how many times it inserted successfully?
|||The proc you are calling to do the INSERT can keep track of number of records affected and increment a counter and send back the value at the end through an OUTPUT parameter.
|||Thanks a million...Can you please tell me what adjustment i need to make in stored procedure,to account this record tracking?Currently it has just the simple insert based on some parameter,i send.
Also for the output parameter,will this suffice or what i need to change here.
cmd.Parameters.Add(
newSqlParameter("@.outputVal",SqlDbType.Int));cmd.Parameters[
"@.outputVal"].Direction =ParameterDirection.Output;cmd.ExecuteNonQuery();
return cmd.Parameters["@.outputVal"].value;
|||The code you have to retrieve the OUTPUT value looks good. If you can post the proc I can look at it.|||
Thanks ..
This is one of the stored proc,i have which gets executed in the loop
ALTER PROCEDURE
dbo.IS_spInsertToHardware@.insertItem
nvarchar(50)AS
insert intotblProducts (Product)values(@.insertItem)RETURN|||Oh. So you are calling the proc for each insert?|||Yes...inside the function,this is how it is : value1, value2, value3, value4 are the values which user can enter in text boxes..at a time user can enter max 4 values and on click of update,it gets added to the dropdownlist.i don't know any better way to do it..
string
[] textValues =newstring[] { value1, value2, value3, value4 };if ((value1 !=string.Empty) || (value2 !=string.Empty) ||(value3 !=
string.Empty) || (value4 !=string.Empty)){
for (int i = 0; i < textValues.Length; i++){
if (textValues[i] !=string.Empty){//some additional condition which i need to check
if ((id1 > 0) && (id2 == 0)){ retVal = invInsert.insertData(id1, textValues[i], sproc);}
|||So you are making up to 4 trips for each INSERT? There is a better way of doing it all in one trip. Concatenate all the values into one string and send it to the proc. In your proc, parse the string and strip out each value and do the INSERT. Check for @.@.ERRPR after the INSERT and if its 0, increment a counter. After all the INSERTs are done, return the counter value and it should have the number of successfull INSERTs.
Search this forum for some code on parsing the string and extracting the values. I think I posted some code here.
|||Thanks Dinaker,,i will look into it.....yes...i don't like making up to 4 trips to DB either for each insert..but i couldn't find any better way of doing it when i was coding..so did it this way...
|||Hi,
In my opinion, I would put a counter in my C# or VB code and accumulate the return value from ExecuteNonQuery.
It would be more easy than calculating in the stored procedure.
HTH.
|||You are right...thats what i have done at this point..inside my db class i haveint n = cmd.ExecuteNonQuery().. in my C# code i check if n>0,if it is i increment the counter ...But i also would like to learn how it can be done inside the stored procedure...i haven't found yet,.how to parse the string in stored procedure and loop through each value and get the success count,as dinaker suggested...thanks|||
Kevin Yu - MSFT:
In my opinion, I would put a counter in my C# or VB code and accumulate the return value from ExecuteNonQuery. It would be more easy than calculating in the stored procedure.
Kevin
Do you really think making 4 trips do the DB is better than one? The increment can be done either at the application level or in the proc.
|||Hi,
Of course, this is not a good practice. I would put the validation for these 4 strings in the stored procedure and make the 4 strings as parameters. Then the stored procedure will return rows affected at once.
Friday, March 9, 2012
nullable and unique column
unique value.
it turned out that I could only insert one null record for
this column,
I had 'duplicate key...' error when trying to insert the
second null for this column.
what is the way to make a column that is nullable for more
than one record, and
is unique if the data is not null?
thanks!One way to achieve that is to create a view that selects only the
non-NULL rows and create a unique clustered index on the relevant
columns.
HTH,
Gert-Jan
amy wrote:
> I created a table and one of its column can be null, or
> unique value.
> it turned out that I could only insert one null record for
> this column,
> I had 'duplicate key...' error when trying to insert the
> second null for this column.
> what is the way to make a column that is nullable for more
> than one record, and
> is unique if the data is not null?
> thanks!|||Hi Amy,
Thank you for using MSDN Newsgroup! My name is Billy and it's my pleasure to assist you
with your issue.
From your description, I understand that you would like to allow multiple nulls in a UNIQUE
column. Have I fully understood you? If there is anything I misunderstood, please feel free to
let me know.
Unfortunately, this feature is not allowed in relational databases that adhere to the SQL
standard. As we know, Null, by definition is an "unknown" value and is not equal to any other
value even the null itself.
However, UNIQUE constraint regards Null as other normal values. In this way, a unique
column only allow one Null. On the other hand, for the purposes of unique indexes, SQL Server
also treats all NULLs as equal so you cannot have more than one.
It's better to not allow Null in a unique column as SQL Server allows only one null (I understand
this may be a problem when you insert rows and left that column null/blank). If you need to
perform like that, I recommend you use some check mechanism such as triggers to check
rows inserted into the table first to avoid the duplicated nulls errors.
Amy, does this answer your question? If there is anything more I can do to assist you, please
feel free to post it in the group
Best regards,
Billy Yao
Microsoft Online Support
----
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
Please reply to newsgroups only. Thanks.|||Thank you Billy Yao !
Yes, now I'm using a trigger to check the data during
insert.
-amy
>--Original Message--
>Hi Amy,
>Thank you for using MSDN Newsgroup! My name is Billy and
it's my pleasure to assist you
>with your issue.
>From your description, I understand that you would like
to allow multiple nulls in a UNIQUE
>column. Have I fully understood you? If there is anything
I misunderstood, please feel free to
>let me know.
>Unfortunately, this feature is not allowed in relational
databases that adhere to the SQL
>standard. As we know, Null, by definition is an "unknown"
value and is not equal to any other
>value even the null itself.
>However, UNIQUE constraint regards Null as other normal
values. In this way, a unique
>column only allow one Null. On the other hand, for the
purposes of unique indexes, SQL Server
>also treats all NULLs as equal so you cannot have more
than one.
>It's better to not allow Null in a unique column as SQL
Server allows only one null (I understand
>this may be a problem when you insert rows and left that
column null/blank). If you need to
>perform like that, I recommend you use some check
mechanism such as triggers to check
>rows inserted into the table first to avoid the
duplicated nulls errors.
>Amy, does this answer your question? If there is anything
more I can do to assist you, please
>feel free to post it in the group
>Best regards,
>Billy Yao
>Microsoft Online Support
>----
>Get Secure! - www.microsoft.com/security
>This posting is provided "as is" with no warranties and
confers no rights.
>Please reply to newsgroups only. Thanks.
>
>.
>
Wednesday, March 7, 2012
Null Values
I set up a new SQL database file, in that file I allowed nulls, When I went through code to save the record, the exception is saying it doesnt allow nulls.
Before I get to involved with SQL, is it a bad practice to use nulls?
If it is what do you enter in place of the null value,
which will lead to more code, right?
Davids Learning SQL
Having and using nulls is not bad practice.....
Your problem maybe that your trying to have a null on your key field........
|||No, the primary key did have a number assigned that did not exist.
I did a msgbox to throw the value back to me just to see in case and it was the number I chose.
I intentionally did not enter a value into a int field to see what would happen.
I opened the database file, and allow nulls is checked for the field and the field is not the primary
Any thoughts?
Davids Learning
|||Is the field a date field?|||I remember running in to similar problem, but I am not sure if it is exactly the same. The work around (or the solution for that matter) was I opened the DataSet containing my dataTable. Clicked on the field in that dataTable and in properties, I Changed 'NullValue' property to (Nothing). By default, it's set to (Throw Exception), which forces the dataSet to throw exception even if its AllowDBNull is set to true. See if that solves your issue.|||is there a way to default to "Nothing" instead of throwing an exception?
I wont be able to try your suggestion until Monday, when I get back to my server at work.
Thanks
Davids Learning
|||Move the thread in this forum in order to get better answers.|||That depends, what does nothing mean in your case ? Normally nothing is equal to NULL when "nothing" is entered.Jens K. Suessmeyer.
http://www.sqlserver2005.de
|||
Hey, sorry for the delay, been having ticker problems, Im back now
What I was getting at was to have the designer default or not check for null instead of throwing exceptions.
There is not but 1 field that needs not to be null and thats the primary field and I am taking care of that.
Is there a way to accomplish that.
The tables that I am dealing with contain a lot of fields and it will take some time to go through and change.
Thanks Again
Davids Learning
|||Hi,what about setting a default value in SQL Server then ?
Jens K. Suessmeyer.
http://www.sqlserver2005.de
|||
I need to post what I did to mask the problem
I went into the table designer in VB and changed how each column handles nulls, basically setting them to not throw an exception on dbnulls.
I didnt want values in some fields intentionally because of other factor, like dates, if I set a default date in an expiration field(that would be bad).
I will on the other hand have to watch and plan on handling nulls now, and thats alright.
Thanks
Davids Learning
|||To me, it looked like a VB bug, but I will leave the judgement for you guys. If I allow nulls in my database table and create a typed DataSet from that table, the DataSet throws an error when it encounters a null value. If the DataSet's AllowDBNull is set to true, then it should default to 'Nothing' for NullValue property. It does not seem logical to me (Allow DBNull, but throw an error!!!). For those who want to reproduce the problem, use bound DataGridview with some fields that allow DBNull and try to save without entering data in those fields.|||Glad to see someone in the same boat
Davids Learning
Saturday, February 25, 2012
Null record
here is my problem: I have two tables, one containing dates and the other dates + data which I'd like to join to get Null rows when no data is found. I would like to get a recordset holding tha values based upon their Id using a left join to fill with NULL when data is missing. I tried with the query below, but I cannot get the Null record showing up. It works without the WHERE clause, but then I'll get all the rows. Any suggestions would be greatly appreciated!
Thank you very much !
Table master
'Fulldate'
'2004-08-10 08:00:00'
'2004-08-10 07:00:00'
'2004-08-10 06:00:00'
Table cab_a
'Fulldate','Id','MeanValue'
'2004-08-10 08:00:00','4','0.9'
'2004-08-10 08:00:00','3','0.5'
'2004-08-10 08:00:00','2','0.01'
'2004-08-10 08:00:00','1','0.14'
.......... missing ............
'2004-08-10 06:00:00','4','0.2'
'2004-08-10 06:00:00','3','0.2'
'2004-08-10 06:00:00','2','0.02'
'2004-08-10 06:00:00','1','0.14'
SQL query
SELECT master.Fulldate, MeanValue FROM master left join cab_a using (Fulldate) WHERE id=3 ORDER BY Fulldate DESC;
'2004-08-10 06:00:00','0.2'
'2004-08-10 08:00:00','0.5'
' The recordset I would like to get
'2004-08-10 06:00:00','0.2'
'2004-08-10 07:00:00','NULL'
'2004-08-10 08:00:00','0.5'
Regards,
Paolo SaudinHi,
This is a perfect example to illustrate the difference between ON and WHERE.
SQL> create table a
2 (
3 name number(2)
4 );
Table created.
SQL> insert into a values (1);
1 row created.
SQL> insert into a values (2);
1 row created.
SQL> create table b as select * from a;
Table created.
SQL> alter table b add value number(2);
Table altered.
SQL> update b set value = name*10;
2 rows updated.
SQL> select a.name, NVL(b.name, -1), NVL(b.value, -1)
2 from a
3 LEFT OUTER JOIN
4 b ON
5 a.name = b.name
6 where b.value = 10;
NAME NAME VALUE
---- ---- ----
1 1 10
SQL> select a.name, NVL(b.name, -1), NVL(b.value, -1)
2 from a
3 LEFT OUTER JOIN
4 b ON
5 a.name = b.name AND
6 b.value = 10;
NAME NVL(B.NAME,-1) NVL(B.VALUE,-1)
---- ----- -----
1 1 10
2 -1 -1
SQL> select a.name, NVL(V.name, -1), NVL(V.value, -1)
2 from a
3 LEFT OUTER JOIN
4 (Select b.name, b.value
5 from b
6 where value = 10) V ON
7 a.name = V.name;
NAME NVL(V.NAME,-1) NVL(V.VALUE,-1)
---- ----- -----
1 1 10
2 -1 -1
Thank You.|||It works perfectly,
Thank you very much !!
Paolo
Monday, February 20, 2012
NULL issue
Instead of a record number being assigned to the first column of each row,
the database displays <NULL> in the column. How can I get the record number
to display in the database?
When I run my second PHP script, it retreives the data from the database. It
needs to display the data with the database record number, but instead
displays <NULL>.
$tday = date('Ymd');
$name2 = $HTTP_POST_VARS["name"];
$empNum = $HTTP_POST_VARS["empNum"];
$email = $HTTP_POST_VARS["email"];
$deptSta2 = $HTTP_POST_VARS["deptSta"];
$subject2 = $HTTP_POST_VARS["subject"];
$comments2 = $HTTP_POST_VARS["comments"];
$mailList = $HTTP_POST_VARS["mailList"];
$result=odbc_exec($connection,"INSERT INTO contact VALUES(NULL, '$tday',
'$name2', '$empNum', '$email', '$deptSta2', '$subject2', '$comments2',
'$mailList', 'N')");what is the first column? and wht does the insert or update stmnt look like?
"Npeart1" wrote:
> I have a PHP web form that takes data and posts it to the SQL database.
> Instead of a record number being assigned to the first column of each row,
> the database displays <NULL> in the column. How can I get the record numbe
r
> to display in the database?
> When I run my second PHP script, it retreives the data from the database.
It
> needs to display the data with the database record number, but instead
> displays <NULL>.
> $tday = date('Ymd');
> $name2 = $HTTP_POST_VARS["name"];
> $empNum = $HTTP_POST_VARS["empNum"];
> $email = $HTTP_POST_VARS["email"];
> $deptSta2 = $HTTP_POST_VARS["deptSta"];
> $subject2 = $HTTP_POST_VARS["subject"];
> $comments2 = $HTTP_POST_VARS["comments"];
> $mailList = $HTTP_POST_VARS["mailList"];
>
> $result=odbc_exec($connection,"INSERT INTO contact VALUES(NULL, '$tday',
> '$name2', '$empNum', '$email', '$deptSta2', '$subject2', '$comments2',
> '$mailList', 'N')");
>