Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Thursday, March 29, 2012

Getting a Return value from a Function.

Im a self proclaimed newb and Im stuck on returning a value from a function. I want to get the AttendID that the SQL statement returns and dump it into strAttendID:Response.Redirect("ClassSurvey.aspx?Pupil=" & strAttendID)
I cant seem to accomplish this. It returns nothing. Please help.
TIA,
Stue
<code>
Function Get_AttendID(ByVal strAttendIDAsString)As SqlDataReader
Dim connStringAsString = ConfigurationSettings.AppSettings("ClassDB")
Dim sqlConnAsNew SqlConnection(connString)
Dim sqlCmdAs SqlCommand
Dim drAs SqlDataReader

sqlConn.Open()
Dim strSQLAsString = "Select AttendID from attendees Where FirstName=@.FirstName and LastName=@.LastName and classbegdt = @.classbegdt and survey = '0'"

sqlCmd =New SqlCommand(strSQL, sqlConn)

sqlCmd.Parameters.Add("@.FirstName", SqlDbType.VarChar, 50)
sqlCmd.Parameters("@.FirstName").Value = tbFirstName.Text
sqlCmd.Parameters.Add("@.LastName", SqlDbType.VarChar, 50)
sqlCmd.Parameters("@.LastName").Value = tbLastName.Text
sqlCmd.Parameters.Add("@.classbegdt", SqlDbType.DateTime, 8)
sqlCmd.Parameters("@.classbegdt").Value = calBegDate.SelectedDate.ToShortDateString
dr = sqlCmd.ExecuteReader()
dr.Close()
sqlConn.Close()

Return dr

EndFunction
</code>

Why are you returning a datareader if all you want is the attend id and why are you even using the datareader at all when all you are looking for is one value.
The best way would be to use executescalar method and return the value. excuse the sample code because it is C#

publicstring AttendID()
{
SqlConnection myConnection =new SqlConnection(ConfigurationSettings.AppSettings("ClassDB"));
string strSQL = "Select AttendID from attendees Where FirstName=@.FirstName and LastName=@.LastName and classbegdt = @.classbegdt and survey = '0'";
SqlCommand myCommand =new SqlCommand(strSQL, myConnection);
myCommand.Parameters.Add("@.FirstName", SqlDbType.VarChar, 50);
myCommand.Parameters("@.FirstName").Value = tbFirstName.Text;
myCommand.Parameters.Add("@.LastName", SqlDbType.VarChar, 50);
myCommand.Parameters("@.LastName").Value = tbLastName.Text;
myCommand.Parameters.Add("@.classbegdt", SqlDbType.DateTime, 8);
myCommand.Parameters("@.classbegdt").Value = calBegDate.SelectedDate.ToShortDateString();

return myCommand.ExecuteScalar().ToString();
}


|||Thanks Mansoorl! I tried that and it worked. In response to your question about the datareader, the reason I went this route is because I have another function wich requires pulling 2 values. So i was in that mindset. I didnt know about the ExecuteScalar though so thanks for educating me.
Do you mind explaining how i might go about returning 3 values via the data reader if:
Select FirstName, LastName, Company from TBClassSurvey Where AttendID=@.AttendID and SchedID=@.SchedID and survey = '0'";

Thanks again,
Stue
|||publicvoidAttendID()
{
SqlConnection myConnection =new SqlConnection(ConfigurationSettings.AppSettings("ClassDB"));
string strSQL = "Select AttendID from attendees Where FirstName=@.FirstName and LastName=@.LastName and classbegdt = @.classbegdt and survey = '0'";
SqlCommand myCommand =new SqlCommand(strSQL, myConnection);
myCommand.Parameters.Add("@.FirstName", SqlDbType.VarChar, 50);
myCommand.Parameters("@.FirstName").Value = tbFirstName.Text;
myCommand.Parameters.Add("@.LastName", SqlDbType.VarChar, 50);
myCommand.Parameters("@.LastName").Value = tbLastName.Text;
myCommand.Parameters.Add("@.classbegdt", SqlDbType.DateTime, 8);
myCommand.Parameters("@.classbegdt").Value = calBegDate.SelectedDate.ToShortDateString();

SqlDataReader myReader = myCommand.ExecuteReader();
myReader.Read();
string FirstName = myReader["FirstName"].ToString();
string LastName = myReader["LastName"].ToString();
string Company = myReader["Company"].ToString();
myReader.Close();
myConnection.Close();
}
The above code assumes you got something back in result of the query. If there is a possiblity for blank records make sure you use if (myReader.Read()) constuct.
Cheers,|||Thanks again mansoorl! I appretiate you educating me.
Take care,
Stue

Monday, March 26, 2012

Getstring question

how can i add two columns in each row (both strings) in a table only using getstring?

i'm getting an error from this statement... thanks

dim row as string

while dr.read()

problem with this statment

--->> row = dr.getstring(1) + dr.getstring(2)

end whileExactly what is the error message?|||the error message is

Index was outside the bounds of the array.|||Index was outside the bounds of the array.|||Can you verify that your query is in fact returning 2 fields?|||select lastname,firstname from employees

i'm using the northwind db in sql server 2000|||I am not familiar with VB.NET syntax, but in C#, GetString() is zero based, so you'd have:

row = dr.getstring(0) + dr.getstring(1)

Not sure if its the same in VB.NET, but you might want to give that a try.

Wednesday, March 21, 2012

GetDate() Does not Return Milliseconds ?

Ladies / Gentlemen
If you run the following select statement you will find as I did
that GetDate() does no obtain Milliseconds - Why Not and can I use something
that does ?
Mark Moss
SELECT CONVERT(varchar(20), GETDATE(), 113) AS Expr2,
CONVERT(varchar(20), GETDATE(), 109) AS Expr1Hi Mark
The getdate() function ALWAYS returns milliseconds. It's only when you
convert it to character that the milliseconds might be discarded.
In this situation, you have not provided enough space to hold the
milliseconds. Try varchar(25) instead of varchar(20)
--
HTH
Kalen Delaney, SQL Server MVP
www.solidqualitylearning.com
"msnews.microsoft.com" <markmoss@.adelphia.net> wrote in message
news:%234V0y1ucGHA.4428@.TK2MSFTNGP03.phx.gbl...
> Ladies / Gentlemen
> If you run the following select statement you will find as I did
> that GetDate() does no obtain Milliseconds - Why Not and can I use
> something that does ?
>
> Mark Moss
>
> SELECT CONVERT(varchar(20), GETDATE(), 113) AS Expr2,
> CONVERT(varchar(20), GETDATE(), 109) AS Expr1
>|||Mark,
GETDATE() returns a datetime, which includes a millisec part. If you do
"SELECT DATEPART(ms,GETDATE())" you'll see this. Your problem is that
you're converting to a 20 char string and the millisec bit it getting
truncated. It's a string truncation issue, not a datetime issue. Try
using a varchar(30) or something bigger.
Also, you ought to use CURRENT_TIMESTAMP rather than GETDATE() as
CURRENT_TIMESTAMP is the ANSI equivalent (GETDATE() is Microsoft
proprietary) and in the majority of cases you should leave presentation
of the data up to the presentation layer (ie. the client) rather than
the DB engine.
*mike hodgson*
http://sqlnerd.blogspot.com
msnews.microsoft.com wrote:

>Ladies / Gentlemen
> If you run the following select statement you will find as I did
>that GetDate() does no obtain Milliseconds - Why Not and can I use somethin
g
>that does ?
>
>Mark Moss
>
>SELECT CONVERT(varchar(20), GETDATE(), 113) AS Expr2,
>CONVERT(varchar(20), GETDATE(), 109) AS Expr1
>
>|||The best way to get the format you want is through an user interface. VB
converts the SQL GETDATE() with milliseconds very well.
You can use
SELECT CONVERT(varchar(20), GETDATE(), 113) + '.' + CONVERT(VARCHAR(3),
DATEPART(MS,GETDATE())) AS Expr2,
CONVERT(varchar(20), GETDATE() , 109)+ '.' + CONVERT(VARCHAR(3),
DATEPART(MS,GETDATE())) AS Expr1
and your milliseconds will show
Thanks Kllyj64
"msnews.microsoft.com" wrote:

> Ladies / Gentlemen
> If you run the following select statement you will find as I did
> that GetDate() does no obtain Milliseconds - Why Not and can I use somethi
ng
> that does ?
>
> Mark Moss
>
> SELECT CONVERT(varchar(20), GETDATE(), 113) AS Expr2,
> CONVERT(varchar(20), GETDATE(), 109) AS Expr1
>
>|||lol..or you could just change the size of your VARCHAR()....
--
Thanks Kllyj64
"kllyj64" wrote:
> The best way to get the format you want is through an user interface. VB
> converts the SQL GETDATE() with milliseconds very well.
> You can use
> SELECT CONVERT(varchar(20), GETDATE(), 113) + '.' + CONVERT(VARCHAR(3)
,
> DATEPART(MS,GETDATE())) AS Expr2,
> CONVERT(varchar(20), GETDATE() , 109)+ '.' + CONVERT(VARCHAR(3),
> DATEPART(MS,GETDATE())) AS Expr1
> and your milliseconds will show
>
> --
> Thanks Kllyj64
>
> "msnews.microsoft.com" wrote:
>|||Just increase VARCHAR to 40. 20 is too short and thus the reason why
msec is left off.
Mark
On Mon, 8 May 2006 16:19:10 -0600, "msnews.microsoft.com"
<markmoss@.adelphia.net> wrote:

>Ladies / Gentlemen
> If you run the following select statement you will find as I did
>that GetDate() does no obtain Milliseconds - Why Not and can I use somethin
g
>that does ?
>
>Mark Moss
>
>SELECT CONVERT(varchar(20), GETDATE(), 113) AS Expr2,
>CONVERT(varchar(20), GETDATE(), 109) AS Expr1
>

Getdate Function

How do I modify the statement listed below to give me the date with the time
of 12:00 AM.
declare @.Yester_day smalldatetime
set @.Yester_day = (select getdate()-1)
print @.Yester_day '
Output
2005-08-30 10:48:12.127Select DATEADD(hh,-12,CONVERT(varchar(50),getdate(),112))
--
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"Joe K." wrote:

> How do I modify the statement listed below to give me the date with the ti
me
> of 12:00 AM.
>
> declare @.Yester_day smalldatetime
> set @.Yester_day = (select getdate()-1)
> print @.Yester_day '
> Output
> 2005-08-30 10:48:12.127
>
>|||DECLARE @.Yesterday SMALLDATETIME -- why the underbar?
SET @.Yesterday = DATEDIFF(DAY,1,GETDATE())
SELECT @.Yesterday
Or more elaborately:
DECLARE @.Yesterday SMALLDATETIME
SET @.Yesterday = DATEADD(DAY, -1, DATEDIFF(DAY, 0, GETDATE()))
SELECT @.Yesterday
"Joe K." <Joe K.@.discussions.microsoft.com> wrote in message
news:7F1A26A7-E861-420C-B318-4F57A6C31425@.microsoft.com...
> How do I modify the statement listed below to give me the date with the
> time
> of 12:00 AM.
>
> declare @.Yester_day smalldatetime
> set @.Yester_day = (select getdate()-1)
> print @.Yester_day '
> Output
> 2005-08-30 10:48:12.127
>
>|||declare @.Yester_day smalldatetime
set @.Yester_day = (select cast (floor(cast (getdate()-1 as float))as
datetime))
print @.Yester_day
"Joe K." wrote:

> How do I modify the statement listed below to give me the date with the ti
me
> of 12:00 AM.
>
> declare @.Yester_day smalldatetime
> set @.Yester_day = (select getdate()-1)
> print @.Yester_day '
> Output
> 2005-08-30 10:48:12.127
>
>

Monday, March 19, 2012

get value from SQL server 2005 select statement with datareader

I just want a simple datareader, that i can read the value returned from a select statement executed on a SQL server 2005 db.

The code below should work in, but email[calc]= rdr[0].ToString(); when i want to read some data a get a exception saying:

System.InvalidOperationException was unhandled by user code
Message="Invalid attempt to read when no data is present."
Source="System.Data"
StackTrace:
at System.Data.SqlClient.SqlDataReader.GetValue(Int32 i)
at System.Data.SqlClient.SqlDataReader.get_Item(Int32 i)
at _Default.Login_Click(Object sender, EventArgs e) in d:\My Documents\Visual Studio 2005\WebSites\WebSite1\Default.aspx.cs:line 47
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

If anybody could advise me where my stupid mistake is then i would highly appreciate it!

SqlConnection conn = new SqlConnection(getConnection());
SqlDataReader rdr = null;

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "SELECT * FROM Customer";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;

try
{
conn.Open();

rdr = cmd.ExecuteReader();

int calc = 0;

Boolean login = false;
string[] email = new string[100];
object[] password = new object[100];

while (rdr.HasRows) // or rdr.Read();
{
rdr.Read();
email[calc]= rdr[0].ToString();
password[calc] = rdr["Password"].ToString();
if (UserName.Text.Equals(email[calc]) && Password.Text.Equals(password[calc]))
{
login = true;
}
calc++;
}

}
finally
{
rdr.Close();
}

thanks...

Try this:

if (rdr.HasRows)// or rdr.Read(); {while(rdr.Read()) { email[calc]= rdr[0].ToString(); password[calc] = rdr["Password"].ToString();if (UserName.Text.Equals(email[calc]) && Password.Text.Equals(password[calc])) { login =true; } calc++; } }
Hope this helps.

get user db roles

Hi NG members,
I'm searching for a simple sql statement to get all database roles the
current user. Regards A. SpieringArnd
Look at sp_helprolemember system SP
"Arnd Spiering" <arnd.spiering@.gon.de> wrote in message
news:MPG.1c190eb7205b8a4d989681@.msnews.microsoft.com...
> Hi NG members,
> I'm searching for a simple sql statement to get all database roles the
> current user. Regards A. Spiering

Get Unique Values in a group statement

Hi,
Suppose a table [Inventory]:

Item Color Quantity
------- ------- --------
Table Blue 10
Table Red 20
Table Yellow 30
Chair Blue 40
Chair Red 50

I'm wondering if there is a group state like this:
Select Item, ?Function(Color), Sum(Quantity) From Inventory Group by Item
which returns this:

Table Blue,Red,Yellow 60
Chair Blue,Red 90

Does anyone has an idea how this can be achieved?

Regards,
Manolis PerrakisDoes anyone has an idea how this can be achieved?Ooh ooh ooh - me - pick me!

http://sqljunkies.com/WebLog/amachanic/archive/2004/11/10/5065.aspx?Pending=true
:)|||Hi,
thanks for the answer.
I don't think is a good idea to run a query for each record. This will consume a lot of resources, and in my case when having to do with large tables and a lot of resulted records this is not an option.
I was hoping there was an internal function, of if it can be defined such a funtion. For example if AVG is used the MSSQL access all the records keep their values and at the end calculates the result. Instead of adding these values I was hoping to create a string which can be compared internally without having to execute another query.
Reagrds,
Manolis Perrakis|||Search the text for "Yep, me too... until I tuned it and then it did it all in 5 seconds flat on a million rows for 50,000 CustID's. " and see if the suggested optimisations are appropriate for you.

Ultimately you are taking relational data and trying to put it into a context that violates first normal form so it is not surprising that SQL does not provide a built in function to do this.

The other alternative is that you can write (if you are using SQL Server 2005) your own CLR aggregate functions. I don't really know anything about these (including how they perform) but you could try researching to see if it is applicable to your needs.|||Yes you are right. There is the article:
http://msdn2.microsoft.com/en-us/library/ms131056.aspx
that does exactly this.
However I use MSSQL2000.|||However I use MSSQL2000.I suspect you are probably stuffed then.

I like the article I linked to as it demonstrates, and compares, two methods of skinning this particular cat. In particular it focuses on performance and, as I pointed out, later on one contributer offers a few refinements that get a decent performance for a medium sized table (1 million rows).

I doubt you will find any alternative technique that will substantially outperform the solution in the article but maybe one of the posters here will surprise me :)

BTW - what sort of performance did you get?|||Hi,
I want to use this operation in some aggregate complex queries that are already slow. Apart from this in order to get the correct data when calculating these value I must run these queries with other criteria also, such as date range which must be used in order to get the correct records. Therefore it's quite complicated. However I will try it the next days.
Regards,
Manolis|||I don't suppose there is a finite, known and ideally small number of possible "color" values?|||No, the "color" values is large, about 25000.|||you can get these things in 25000 different colours? Henry Ford would turn in his grave...|||I don't think is a good idea to run a query for each record. Just thought - I don't know how SQL Server optimises the query for this but presumably does as you suggest - runs the function for each record and then groups on the results. So you could improve things (I imagine) with something like:

SELECT Item, dbo.MyConcatFunction(Item) AS CSV_Colors, TotalQuantity
FROM (
SELECT Item, SUM(Quantity) AS TotalQuantity
FROM [Inventory]
GROUP BY Item
) AS Distinct_Items
Call the function once per item rather than once per row.

Monday, March 12, 2012

Get the Top 3 record in same table.


Hi all,

I have some questions about sql statement. Is there anyway to get top 3 record for each item in the same table? I use before 'top' but it will give me the top value base on the price. Can someone give me an advice on this?

Thanks in advance.

Example:

Table 1

Item Name Price Date
A $10.00 15 Jan 2007
A $8.50 17 May 2006
A $8.00 1 Jan 2006
A $7.80 24 Sep 2005
B $12.20 2 Jan 2007
B $12.00 10 Oct 2006


I want get the result as below base on the example table 1. (Top3 Record for each item)

A $10.00 15 Jan 2007
A $8.50 17 May 2006
A $8.00 1 Jan 2006
B $12.20 2 Jan 2007
B $12.00 10 Oct 2006

select *
from tbl t
where price in (select top 3 price from tbl x where x.item_name = t.item_name)|||SELECT [Item Name], Price, Date
FROM (SELECT ROW_Number()OVER(PARTITION BY [Item Name] ORDER BY PRICE) as RowNum,[Item Name], Price, Date
FROM top3$)AS t1
WHERE RowNum<=3|||

Hi,

It really helps me solve my problem.

Thanks alot.

Wednesday, March 7, 2012

Get the closest date

Hello,

I need help in writing a SQL statement in MS SQL Server 2000 to select
the latest date (i.e., the date closest to or equal to the current date)
for a given date.

For example, in a table I have the following records:
Date Exchange-Rate
01/Sep/03 0.55
05/Sep/03 0.59

If the given date is 02/Sep/03, then the rate 0.55 should be return.
If the given date is 03/Sep/03, then the rate 0.55 should be return.
If the given date is 04/Sep/03, then the rate 0.59 should be return.

Thanks in advanced,

Benny

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!Benny Chow (benny@.stg.net.nz) writes:
> I need help in writing a SQL statement in MS SQL Server 2000 to select
> the latest date (i.e., the date closest to or equal to the current date)
> for a given date.
> For example, in a table I have the following records:
> Date Exchange-Rate
> 01/Sep/03 0.55
> 05/Sep/03 0.59
> If the given date is 02/Sep/03, then the rate 0.55 should be return.
> If the given date is 03/Sep/03, then the rate 0.55 should be return.
> If the given date is 04/Sep/03, then the rate 0.59 should be return.

Next time, please include CREATE TABLE statements for the tables you
are working with and INSERT statements with sample data. This makes it
possible to post a tested solution.

Thus, this solution is untested:

SELECT exchangerage, date
FROM rates
WHERE date = (SELECT MAX(date)
FROM rates
WHERE date <= @.date)

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||CREATE TABLE ExchangeRates (rdate DATETIME PRIMARY KEY, exchangerate
DECIMAL(10,2) NOT NULL)
INSERT INTO ExchangeRates VALUES ('20030901',0.55)
INSERT INTO ExchangeRates VALUES ('20030905',0.59)

DECLARE @.dt DATETIME
SET @.dt = '20030902'

Here's one method:

SELECT exchangerate
FROM ExchangeRates
WHERE rdate =
(SELECT MIN(rdate)
FROM ExchangeRates
WHERE ABS(DATEDIFF(DAY,@.dt,rdate))=
(SELECT MIN(ABS(DATEDIFF(DAY,@.dt,rdate)))
FROM ExchangeRates))

Or you can use TOP:

SELECT TOP 1 exchangerate
FROM ExchangeRates
ORDER BY ABS(DATEDIFF(DAY,@.dt,rdate)), rdate

Personally, I would avoid TOP because it's a MS proprietary extension to
SQL.

--
David Portas
----
Please reply only to the newsgroup
--|||Benny wants the closest, before or after the specified date according to his
example.

--
David Portas
----
Please reply only to the newsgroup
--|||Thanks David, this is exactly what I needed. :)

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Benny,

This might be a little more efficient than other
solutions, but it's not as simple:

select top 1 exchangerate
from (
select exchangerate, pref
from (
select top 1 exchangerate, 1 as pref
from (
select top 3 rdate, exchangerate
from ExchangeRates E1
where E1.rdate >= (
select max(rdate) as lastBefore
from ExchangeRates E2
where E2.rdate < @.dt
)
order by rdate
) X
order by case when rdate < @.dt then @.dt - rdate else rdate - @.dt end
) X1
union all
select exchangerate, pref
from (
select top 1 exchangerate, 2 pref
from ExchangeRates
order by rdate
) Y
) T
order by pref

-- Steve Kass
-- Drew University
-- Ref: 250CBB08-57AE-45C7-97F2-AF26AFC368ED

Benny Chow wrote:
> Hello,
> I need help in writing a SQL statement in MS SQL Server 2000 to select
> the latest date (i.e., the date closest to or equal to the current date)
> for a given date.
> For example, in a table I have the following records:
> Date Exchange-Rate
> 01/Sep/03 0.55
> 05/Sep/03 0.59
> If the given date is 02/Sep/03, then the rate 0.55 should be return.
> If the given date is 03/Sep/03, then the rate 0.55 should be return.
> If the given date is 04/Sep/03, then the rate 0.59 should be return.
> Thanks in advanced,
> Benny
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!|||David Portas (REMOVE_BEFORE_REPLYING_dportas@.acm.org) writes:
> Benny wants the closest, before or after the specified date according to
> his example.

Funny guy. :-) Some of our tables for prices and rates are sparse in a
similar manner, but we always assume that a value applies until a new
value comes in. So I assume he wanted the same.

But had Benny included CREATE TABLE and sample data in INSERT statements,
I would have seen that my solution was wrong!

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||> Funny guy. :-) Some of our tables for prices and rates are sparse in a
> similar manner, but we always assume that a value applies until a new
> value comes in. So I assume he wanted the same.

I agree that it seems like an unusual requirement. Although I suppose if you
wanted to calculate the value of a currency deal retrospectively it might
make sense to take the closest rate as the best approximation. But IANAA.

> But had Benny included CREATE TABLE and sample data in INSERT statements,
> I would have seen that my solution was wrong!

I know that feeling! :|

--
David Portas
----
Please reply only to the newsgroup
--|||Thanks for all your guys help ^^.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Get SQL Statement that caused the change?

I'd like to audit the changes to a table and I'd like to keep track of
the sql statements used to change the table. I know how to get the
system user and the app name, but is it possible to recover the sql as
well? Thanks for any help.
-JohnSee if this helps:
http://vyaskn.tripod.com/tracking_s...by_triggers.htm
--
HTH,
Vyas, MVP (SQL Server)
SQL Server Articles and Code Samples @. http://vyaskn.tripod.com/
"John Baima" <john@.nospam.com> wrote in message
news:vmdde11i919mouii6jgug74r7n7ms3f17f@.
4ax.com...
> I'd like to audit the changes to a table and I'd like to keep track of
> the sql statements used to change the table. I know how to get the
> system user and the app name, but is it possible to recover the sql as
> well? Thanks for any help.
> -John|||Maybe this will help?
CREATE TABLE #foo
(
EventType SYSNAME,
Parameters SYSNAME,
EventInfo NTEXT
)
DECLARE @.sql NVARCHAR(4000)
SET @.sql = N'DBCC INPUTBUFFER('+RTRIM(@.@.SPID)+') WITH TABLERESULTS'
INSERT #foo EXEC(@.sql)
SELECT EventInfo FROM #foo
DROP TABLE #foo|||Thanks, that's perfect. -John
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote:

>Maybe this will help?
>CREATE TABLE #foo
>(
> EventType SYSNAME,
> Parameters SYSNAME,
> EventInfo NTEXT
> )
>DECLARE @.sql NVARCHAR(4000)
>SET @.sql = N'DBCC INPUTBUFFER('+RTRIM(@.@.SPID)+') WITH TABLERESULTS'
>INSERT #foo EXEC(@.sql)
>SELECT EventInfo FROM #foo
>DROP TABLE #foo
>|||Thanks, that is very useful site in general. -John
"Narayana Vyas Kondreddi" <answer_me@.hotmail.com> wrote:

>See if this helps:
>http://vyaskn.tripod.com/tracking_s...by_triggers.htm|||"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote:

>Maybe this will help?
>CREATE TABLE #foo
>(
> EventType SYSNAME,
> Parameters SYSNAME,
> EventInfo NTEXT
> )
>DECLARE @.sql NVARCHAR(4000)
>SET @.sql = N'DBCC INPUTBUFFER('+RTRIM(@.@.SPID)+') WITH TABLERESULTS'
>INSERT #foo EXEC(@.sql)
>SELECT EventInfo FROM #foo
>DROP TABLE #foo
Thanks, that was great. When I do this, for the EventInfo I get:
sp_executesql;1
for the EventType I get:
RPC Event
and the parameter is 0. Is there anyway to get more information and
know what was passed to sp_executesql, etc? Thanks again.
-John|||If you're using sp_executesql, things might get a little complicated. Also,
DBCC INPUTBUFFER is limited in that it will not contain all the previous
command(s), especially if you are doing non-T-SQL things like changing SET
options, master..xp_cmdshell, etc. Can you provide a full repro (e.g. the
table structure, the statement that caused the change, and what you expect
as output)?
"John Baima" <john@.nospam.com> wrote in message
news:2bshe1h29uqjaf4fpknskifa5hjkqb4qbn@.
4ax.com...
> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote:
>
> Thanks, that was great. When I do this, for the EventInfo I get:
> sp_executesql;1
> for the EventType I get:
> RPC Event
> and the parameter is 0. Is there anyway to get more information and
> know what was passed to sp_executesql, etc? Thanks again.
> -John
>
>
>|||Well, that's the rub. We have someone altering the database and we
would like to know who is doing it. It is not being done by any of the
production programs. The command deletes a single row in a reference
table.
-John
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote:

>If you're using sp_executesql, things might get a little complicated. Also
,
>DBCC INPUTBUFFER is limited in that it will not contain all the previous
>command(s), especially if you are doing non-T-SQL things like changing SET
>options, master..xp_cmdshell, etc. Can you provide a full repro (e.g. the
>table structure, the statement that caused the change, and what you expect
>as output)?
>
>
>"John Baima" <john@.nospam.com> wrote in message
> news:2bshe1h29uqjaf4fpknskifa5hjkqb4qbn@.
4ax.com...
>|||Sounds like a job for profiler, not a trigger or DBCC...
"John Baima" <john@.nospam.com> wrote in message
news:n07ie194j6bib94b9k4vm3sei4qltv5g9v@.
4ax.com...
> Well, that's the rub. We have someone altering the database and we
> would like to know who is doing it. It is not being done by any of the
> production programs. The command deletes a single row in a reference
> table.
> -John
>

Get sql statement for parameter through reporting service

hi,

i'm creating a winform application that communicates with a reporting service server through the SOAP interface.

If a user selects a report and presses a button a generic screen is created where I create all winforms controls like datetimepicker(if parameter type is DateTime) or combobox (if parameter type is String). When the parameter value is String and there are DefaultValues I add every value to the combobox. But when it has no DefaultValues and thus is generated through SQL I want the SQL statement but I can't find that property. Her you got the code to make it more comprehensive.

[CODE]
else if (rp.Type.ToString() == "String")
{
ComboBox combobox = new ComboBox();
ValidValue[] values = rp.ValidValues;
if (values == null)
{
String sqlString =
}
else
{
foreach (ValidValue value in values)
{
combobox.Items.Add(value.Label.ToString());
}
}
VerControl += 30;
combobox.Location = new Point(HorControl, VerControl);
combobox.Width = 200;
this.Controls.Add(combobox);
}
[/CODE]
hope you can help

greetings
Never mind. When asking for the report parameters I changed the boolean ForRendering to true so I get the values for SQL based parameters too! I don't have the sql statement but i get the values that I need

Sunday, February 26, 2012

Get return value of stored procedure in Query Analyzer

Hi. We've got a stored procedure on SQL Server 2000 with a Return statement,
and sending back a number. Is there a way to view the Return value when
executing this procedure in Query Analyzer? Right now, it's just displaying
how many rows were affected. Thanks.What about a PRINT statement prior to your Return statement?
--
Jack Vamvas
___________________________________
Receive free SQL tips - www.ciquery.com/sqlserver.htm
"dw" <cougarmana_NOSPAM_@.uncw.edu> wrote in message
news:u3NDF0dSGHA.792@.TK2MSFTNGP10.phx.gbl...
> Hi. We've got a stored procedure on SQL Server 2000 with a Return
statement,
> and sending back a number. Is there a way to view the Return value when
> executing this procedure in Query Analyzer? Right now, it's just
displaying
> how many rows were affected. Thanks.
>|||example
create proc prTestReturnValue
as
select getdate()
return 5
GO
declare @.i int
exec @.i =prTestReturnValue
select @.i
http://sqlservercode.blogspot.com/|||dw,
declare @.rv int
exec @.rv = dbo.p1 ...
select @.rv
go
See "execute" command/statement in BOL.
AMB
"dw" wrote:

> Hi. We've got a stored procedure on SQL Server 2000 with a Return statemen
t,
> and sending back a number. Is there a way to view the Return value when
> executing this procedure in Query Analyzer? Right now, it's just displayin
g
> how many rows were affected. Thanks.
>
>|||Thank you all for the answers. That's what I needed and it worked
beautifully :)
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:AF2BF839-61D5-48FE-9845-11532AFB82CF@.microsoft.com...
> dw,
> declare @.rv int
> exec @.rv = dbo.p1 ...
> select @.rv
> go
> See "execute" command/statement in BOL.
>
> AMB
> "dw" wrote:
>

Friday, February 24, 2012

get records count

i have this function

it return 0 but the sql statement in the sql query return the right number?how is that

i want to get the number of records any other idea or fix?

PublicFunction UserAlbumPhotoQuota(ByVal userIDAsInteger)AsBoolean

Dim ConnAsNew SqlConnection(ConfigurationManager.ConnectionStrings("Conn").ConnectionString)

Dim strSQLAsString

Dim drAs SqlDataReader

strSQL ="SELECT *, (select count(*) from userAlbumPic where userID=" & userID &") as rec_count from userAlbumPic "

Dim cmdAsNew SqlCommand()cmd =New SqlCommand(strSQL, Conn)

Conn.Open()

dr = cmd.ExecuteReader()

dr.Read()

userQuota = dr("rec_count").ToString

Conn.Close()

EndFunction

PublicFunction UserAlbumPhotoQuota(ByVal userIDAsInteger)AsBoolean
Dim ConnAsNew SqlConnection(ConfigurationManager.ConnectionStrings("Conn").ConnectionString)
Dim strSQLAsString ="select count(*) from userAlbumPic where userID=" & userID
Dim cmdAsNew SqlCommand()cmd =New SqlCommand(strSQL, Conn)
Conn.Open()
userQuota = cmd.ExecuteScalar()
Conn.Close()
EndFunction

Jos

|||

i don't know why it returns 0 ? ?

|||try this:strSQL = "SELECT *, rec_count from userAlbumPic PICSleft join (select userID, count(*) rec_count from userAlbumPic group by userID) usercountson PICS.userID = userCounts.userID"I did not test it but it should work|||

Check whether userID is having the value you are expecting.

Jos

get real value by sql

Hello,
How can I get real value by select statement to some simple function as
follows
select 3/8
The result is 0
Can I get the value (with 3 digits ) :
0.375
(or specific digits, i.e = 2 digits)
0.38 (rounded up)
Thanks :)Since you are dividing integers, the result is an integer. You'll need to
specify a decimal operand to get a result with decimals.

> Can I get the value (with 3 digits ) :
> 0.375
SELECT CAST(3 / 8.0 AS decimal(9,3))

> (or specific digits, i.e = 2 digits)
> 0.38 (rounded up)
SELECT CAST(3 / 8.0 AS decimal(9,2))
Hope this helps.
Dan Guzman
SQL Server MVP
"Eitan M" <no_spam_please@.nospam_please.com> wrote in message
news:%230QkxB$oFHA.3756@.TK2MSFTNGP09.phx.gbl...
> Hello,
> How can I get real value by select statement to some simple function as
> follows
> select 3/8
> The result is 0
> Can I get the value (with 3 digits ) :
> 0.375
> (or specific digits, i.e = 2 digits)
> 0.38 (rounded up)
> Thanks :)
>|||This is caused by "integer math" - if you divide two integers, SQL Server
will round down to the nearest integer. Try the following:
SELECT 3.0 / 8
SELECT CONVERT(DECIMAL(5,2), 3.0/8)
http://www.aspfaq.com/2483
"Eitan M" <no_spam_please@.nospam_please.com> wrote in message
news:%230QkxB$oFHA.3756@.TK2MSFTNGP09.phx.gbl...
> Hello,
> How can I get real value by select statement to some simple function as
> follows
> select 3/8
> The result is 0
> Can I get the value (with 3 digits ) :
> 0.375
> (or specific digits, i.e = 2 digits)
> 0.38 (rounded up)
> Thanks :)
>|||Eitan M wrote:
> Hello,
> How can I get real value by select statement to some simple function
> as follows
> select 3/8
> The result is 0
It would not be if you used
select 3./8

> Can I get the value (with 3 digits ) :
> 0.375
select cast(3./8 as decimal(8,3))

> (or specific digits, i.e = 2 digits)
> 0.38 (rounded up)
>
select cast(3./8 as decimal(8,2))
Bob Barrows
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.

Sunday, February 19, 2012

Get number of results from SqlDataSource

Hi all,

Is there a way of counting the number of results/rows from an SqlDataSource which uses a select statement like: "SELECT * FROM TABLE1".

I need to get this value from the SqlDataSource into theSub Page_Load.

I don't want to bind to any gridviews, repeaters etc. I just want to get the number of rows/results from the SqlDataSource.

Is there a way of doing this?

Thanks

Public cnt as integerProtected Sub SqlDataSource1_Selected(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)Handles SqlDataSource1.Selected cnt = e.AffectedRowsEnd Sub
|||

Thanks, that helped. However I need to get this value many times throughout my sub page_load.

I see this value is calculated when SqlDataSource1 is selected. Is there a way to get this value each time I change the default value of a select parameter, or simply call this sub SqlDataSource1_Selected from the Page_load. Since when I change a select parameter, this then affects the select command statement which is when I need to re-calculate the number of rows (get value of integer cnt).

Im guessing I need to change theHandles SqlDataSource1.Selected to something else?

How could I get this working?

Thanks.

|||

using jMacs code you can then access the Variable cnt in your pageload.

The scope of the variable cnt allows you to access it and use it through out the life of the page in your Page_Load sub, or any other method for that matter. It will be set anytime SqlDataSource1_Selected event is called.

Public cnt as integerProtected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Load'//work with the varialbe cnt here.End SubProtected Sub SqlDataSource1_Selected(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)Handles SqlDataSource1.Selected cnt = e.AffectedRowsEnd Sub

|||

Exactly. Here's some more info on the SqlDataSource.Selected Event -http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.selected(vs.80).aspx