Showing posts with label stuck. Show all posts
Showing posts with label stuck. 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

Tuesday, March 27, 2012

Getting 2 SUMs from the same table

Hi All

I'm really stuck on this one so would appreciate any help you can give.

In essence, I have 1 SQL 2000 table with rows of data logging stock
movement. To differenciate between a stock sale and a stock receipt the
table has a TRANSACTIONTYPE field so that 8,7 equal invoices and 3 equals a
receipt.

I've been asked to report on this data by suming the total qty used on
invoices and the total qty recvd for each stock item, but I can't figure out
how I sum the same rows twice in the one query.

For example, my query is as follows:

select st.stockid as 'STYLE',
s.picture as 'COLOUR',
'' as 'IN FIRST IN LAST WEEK',
'' as 'THIS WEEK IN',
'' as 'TOTAL IN',
'' as 'OUT FIRST OUT LAST WEEK',
SUM(st.quantity) as 'THIS WEEK OUT',
'' as 'TOTAL OUT',
'' as 'REMAINING',
'' as 'TOTAL DIGESTION %'
from stocktransactions st, stock s
where st.stockid = s.stockid and
st.transactiontype in (8,7) and
st.transactiondate >= '2005-07-12 00:00:00' and
st.transactiondate <= '2005-07-12 23:59:59'
group by st.stockid,s.picture
order by st.stockid

Apart from the 'THIS WEEK OUT' column SUMing all of the stock sales by
transactiontype 7,8, I also want the 'THIS WEEK IN' column to SUM all of the
transactions by transactiontype 3, so that I get the following results:

STYLE COLOUR ... THIS WEEK IN ... THIS WEEK OUT ......
IVP Red 12 23
STP Blue 4 15
etc etc

My problem is that I don't want to exclude a stock item if it hasn't got a
row/value for the THIS WEEK IN and/or the THIS WEEK OUT. Am I asking too
much of SQL?

My table schemas are as follows:

create table STOCKTRANSACTIONS
(
STOCKTRANSACTIONID T_STOCKTRANSACTIONSDOMAIN not null
identity(1,1),
TRANSACTIONTYPE smallint not null,
TRANSACTIONDATE datetime null ,
REFERENCE varchar(40) null ,
Comment varchar(255) null ,
STOCKID T_STOCKDOMAIN null ,
DESCRIPTION varchar(255) null ,
UNITOFSALE varchar(20) null ,
WAREHOUSEID T_WAREHOUSESDOMAIN null ,
PEOPLEID T_PEOPLEDOMAIN null ,
AccountID T_AccountsDomain null ,
AgentID T_AgentsDomain null ,
PLRate float null ,
CONTACTID T_CONTACTDETAILSDOMAIN null ,
JOBID T_JOBSDOMAIN null ,
QUANTITY float null ,
CURRENCYID T_CURRENCIESDOMAIN null ,
SELLINGPRICE float null ,
DISCOUNTPERCENT float null ,
COSTPRICE float null ,
MINIMUMPRICE float null ,
TILLID T_TILLSDOMAIN null ,
UserID T_UsersDomain null ,
ClockDate DateTime null ,
TimeStamp TimeStamp ,
constraint pk_stocktransactions primary key (STOCKTRANSACTIONID)
)
go

create table STOCK
(
STOCKID T_STOCKDOMAIN not null,
NAME varchar(40) not null,
PICTURE varchar(40) null ,
WEIGHT float null ,
VOLUME float null ,
BARCODE smallint null ,
NumberOfPriceBreaks SmallInt not null default 1,
STOCKCATEGORYID T_STOCKCATEGORIESDOMAIN null ,
SALESNOMINALID T_NOMINALACCOUNTSDOMAIN null ,
PURCHASENOMINALID T_NOMINALACCOUNTSDOMAIN null ,
SELLINGCOMMENT varchar(255) null ,
INCLUDESELLINGCOMMENT TinyInt null ,
DISPLAYSELLINGCOMMENT TinyInt null ,
COSTCOMMENT varchar(255) null ,
DISPLAYCOSTCOMMENT TinyInt null ,
PRODUCTTRACKING smallint null ,
ITEMTYPE smallint null ,
VALUATIONPRICE float not null default
0.00 ,
INCLUDEINCUSTOMERSTURNOVER TinyInt null ,
INCLUDEINAGENTSTURNOVER TinyInt null ,
SUPERCEDED TinyInt null ,
SUPERCEDEDBY T_STOCKDOMAIN null ,
SUPPLIERID T_PEOPLEDOMAIN null ,
SUPPLIERSTOCKID varchar(40) null ,
SUPPLIERCOMMENT varchar(255) null ,
NEXTSERIALNUMBER int null ,
SERIALNUMBERLENGTH smallint null ,
SERIALNUMBERPREFIX varchar(10) null ,
SERIALNUMBERSUFFIX varchar(10) null ,
SERIALNUMBERPREFIXLENGTH smallint null ,
SERIALNUMBERSUFFIXLENGTH smallint null ,
TIMESTAMP timestamp not null,
constraint pk_stock primary key (STOCKID)
)
go

Thanks

RobbieDont repeat the question
http://groups-beta.google.com/group...e663f7fc429d1a3

Madhivanan|||Robbie,

You have some data types in your schema that aren't really data types.
You have STOCKTRANSACTIONID as a data type of
T_STOCKTRANSACTIONSDOMAIN. Are you using SQL Server? How about
posting with good data types and some inserts so people can help you
better.

Thanks,
Jennifer|||(jennifer1970@.hotmail.com) writes:
> You have some data types in your schema that aren't really data types.
> You have STOCKTRANSACTIONID as a data type of
> T_STOCKTRANSACTIONSDOMAIN. Are you using SQL Server? How about
> posting with good data types and some inserts so people can help you
> better.

I assume that these are so-called user-defined data types created with
sp_addtype.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.aspsql

Wednesday, March 21, 2012

getDate() Formatting and Functions Documentation

I'm trying to do something very simple here but I keep getting stuck becuase I can't find much on getDate() in the documenation. Where, in the documenation, does it talk about truncating times, adding to times and all that good stuf.

Below is what I'm trying to do here: I have a while loop that adds to the starting hour of 6am 15 min until it gets to like 7pm. I do realize at this point that just adding 15 is suppsed to add 15 days based on what I have read, but I'm getting an error when I parse this and since I can't seem to find the docs I don't know what to do next?

Msg 102, Level 15, State 1, Procedure PopulateDatabase, Line 32

Incorrect syntax near '@.TeeTime'.

set ANSI_NULLSONset QUOTED_IDENTIFIERONGO-- =============================================-- Author:Przemek-- Create date: -- Description:-- =============================================ALTER PROCEDURE [dbo].[PopulateDatabase]-- Add the parameters for the stored procedure hereASdeclare @.CourseIDuniqueIdentifierdeclare @.TeeTimeSlotintdeclare @.TeeTimedateTimeBEGINSET NOCOUNT ON;--Course 1 *******************************************************************INSERT INTOCourse (CourseID,Name, Address, PhoneNumber)VALUES(NewID(),'Prospect Lake','123 Prospect St', 2508129832)SET @.CourseID = (SELECT CourseIDFROM CourseWHERE Name ='Prospect Lake')SET @.TeeTimeSlot = 0SET @.TeeTime ='6:00'WHILE @.TeeTimeSlot < 56BEGIN INSERT INTOSchedule (ScheduleID, Course_FK, Date, TeeTime, NumberOfPlayers)VALUES(NewID(), @.CourseID,getDate(), @.TeeTime, Rand(5))@.TeeTime = @.TeeTime + 1ENDEND

Helloprzemeklach,

the problem should instead be on the next line, where you miss the SET keyword when incrementing @.TeeTime.

Documentation is into the Sql Books Online, that is the local sql server help. As for any other MS technology, you can find all the docs online as well, on the MSDN site. Here is a link:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/startsql/getstart_4fht.asp

HTH. -LV

|||

Thanks, as my luck would have it I just figured this out like 2 min before you answered my post. Thanks for the link to the documentation, just what I was looking for.

I still have one more question. I want the column TeeTime to just store 06:00, 06:15 etc but instead it's filling it with 1900-01-01 06:00:00 etc. I know this is because of the smallDateTime datatype but is there a way to truncate this so the column is just filled with smallDateTime datatype but with just the time. If not, no big deal, I can just get my code to truncate the year/date as I use this data to populate controls.

set ANSI_NULLSONset QUOTED_IDENTIFIERONGO-- =============================================-- Author:Przemek-- Create date: 15 August 2006-- Description:Populates Course and Schedule-- tables with bogus data.-- =============================================ALTER PROCEDURE [dbo].[PopulateDatabase]-- Add the parameters for the stored procedure hereASdeclare @.CourseIDuniqueIdentifierdeclare @.TeeTimeSlotintdeclare @.TeeTimesmallDateTimeBEGINSET NOCOUNT ON;--Course 1 *******************************************************************INSERT INTOCourse (CourseID,Name, Address, PhoneNumber)VALUES(NewID(),'Prospect Lake','123 Prospect St', 2508129832)SET @.CourseID = (SELECT CourseIDFROM CourseWHERE Name ='Prospect Lake')SET @.TeeTimeSlot = 0SET @.TeeTime ='06:00:00'WHILE @.TeeTimeSlot < 56BEGIN INSERT INTOSchedule (ScheduleID, Course_FK, Date, TeeTime, NumberOfPlayers)VALUES(NewID(), @.CourseID,getDate(), @.TeeTime, ((Rand()*5)+1))SET @.TeeTime =DATEADD(minute, 15, @.TeeTime)SET @.TeeTimeSlot = @.TeeTimeSlot + 1ENDEND
|||

przemeklach:

> I want the column TeeTime to just store 06:00, 06:15 etc but instead it's filling it with 1900-01-01 06:00:00 etc.

I'm afraid that's it. Both T-Sql and .NET languages don't have a 'time' data type. As you maybe implied, there's the DateTime.ToXYZString methods for handling display.

-LV

|||Ya that's what I thought, thanks for your input.

Friday, March 9, 2012

Get the ColumnName of the Identity in a Table

Hi,
I need to know the name of the Column which is the Identity of a Table.
Below is the query to what point I succeeded. But now I'm stuck.
This query returns all tables with an Identity-Column in a database, crossed
with ALL columns (obviously).
Any suggestions?
TIA,
Michael
SELECT INFORMATION_SCHEMA.TABLES.TABLE_CATALOG,
INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA,
INFORMATION_SCHEMA.TABLES.TABLE_NAME,
INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME,
IDENT_SEED(INFORMATION_SCHEMA.TABLES.TABLE_NAME) AS
IDENT_SEED, IDENT_INCR(INFORMATION_SCHEMA.TABLES.TABLE_NAME)
AS IDENT_INCR,
IDENT_CURRENT(INFORMATION_SCHEMA.TABLES.TABLE_NAME) AS IDENT_CURRENT
FROM INFORMATION_SCHEMA.TABLES INNER JOIN
INFORMATION_SCHEMA.COLUMNS ON
INFORMATION_SCHEMA.TABLES.TABLE_CATALOG =
INFORMATION_SCHEMA.COLUMNS.TABLE_CATALOG AND
INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA =
INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA AND
INFORMATION_SCHEMA.TABLES.TABLE_NAME =
INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
WHERE (IDENT_SEED(INFORMATION_SCHEMA.TABLES.TABLE_NAME) IS NOT NULL)I think just found it:
SELECT TABLE_CATALOG,
TABLE_SCHEMA,
TABLE_NAME,
COLUMN_NAME,
IDENT_SEED(TABLE_NAME) AS IDENT_SEED,
IDENT_INCR(TABLE_NAME) AS IDENT_INCR,
IDENT_CURRENT(TABLE_NAME) AS IDENT_CURRENT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_NAME),COL
UMN_NAME,'IsIdentity')=1
I'm just not sure if this approach will work on Server 2005...
Michael|||How about this?
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
AND TABLE_NAME = 'Orders'
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Michael Maes" <michael@.merlot.com> wrote in message
news:262D812C-5439-49F0-B6CA-C2B4511BF0FD@.microsoft.com...
> Hi,
> I need to know the name of the Column which is the Identity of a Table.
> Below is the query to what point I succeeded. But now I'm stuck.
> This query returns all tables with an Identity-Column in a database, cross
ed
> with ALL columns (obviously).
> Any suggestions?
> TIA,
> Michael
> SELECT INFORMATION_SCHEMA.TABLES.TABLE_CATALOG,
> INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA,
> INFORMATION_SCHEMA.TABLES.TABLE_NAME,
> INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME,
> IDENT_SEED(INFORMATION_SCHEMA.TABLES.TABLE_NAME) AS
> IDENT_SEED, IDENT_INCR(INFORMATION_SCHEMA.TABLES.TABLE_NAME)
> AS IDENT_INCR,
> IDENT_CURRENT(INFORMATION_SCHEMA.TABLES.TABLE_NAME) AS IDENT_CURRENT
> FROM INFORMATION_SCHEMA.TABLES INNER JOIN
> INFORMATION_SCHEMA.COLUMNS ON
> INFORMATION_SCHEMA.TABLES.TABLE_CATALOG =
> INFORMATION_SCHEMA.COLUMNS.TABLE_CATALOG AND
> INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA =
> INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA AND
> INFORMATION_SCHEMA.TABLES.TABLE_NAME =
> INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
> WHERE (IDENT_SEED(INFORMATION_SCHEMA.TABLES.TABLE_NAME) IS NOT NULL)|||Hi Tibor,
Thanks for your reply.
Will this approach also be compatible with 2005?
Regards,
Michael
"Tibor Karaszi" wrote:

> How about this?
> SELECT *
> FROM INFORMATION_SCHEMA.COLUMNS
> WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
> AND TABLE_NAME = 'Orders'
>|||Yep. The purpose of info schema view is not only be stable across versions,
but also across
different DBMS vendors. They are defined in the ANSI SQL standard.
I just ran the query against 2005 April CTP, just to give it a spin...
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Michael Maes" <michael@.merlot.com> wrote in message
news:B85C547B-726F-47A7-84FE-70A0384314CE@.microsoft.com...
> Hi Tibor,
> Thanks for your reply.
> Will this approach also be compatible with 2005?
> Regards,
> Michael
> "Tibor Karaszi" wrote:
>|||Thanks Tibor,
Quite a relief :-)
Michael
"Tibor Karaszi" wrote:

> Yep. The purpose of info schema view is not only be stable across versions
, but also across
> different DBMS vendors. They are defined in the ANSI SQL standard.
> I just ran the query against 2005 April CTP, just to give it a spin...
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>

Friday, February 24, 2012

Get percentage with variation of field values (country names)

Any help here would be greatly appreciated...

Unfortunately, data wasn't filtered prior to getting inserted into this table. Now I am stuck with cleaning it up. I have thought about writing a query to update all the values, but there are just too many variations, including spelling mistakes, so I've ruled that out as a possible solution.
I have a table which has a Country field but the values per record vary. For example US, U.S., USA, United States, UK, United Kingdom, Canada, Can, etc. I'm trying to find the percent of records per country.

Sample table data: mytable
Id Name Country
1 John US
2 James UK
3 Jane United States
4 Mary Canada
5 Jack U.S.
6 Tony United Kingdom
7 Jeff US
8 Tom Canada
9 Beth UK
10 Mark USA
I would like to show
US: 50% --> (includes any variation of US ncluding US, U.S., USA, United States)
UK: 30%
CAN: 20%
I've made several attempts myself with no luck. Thanks in advance.

You have to clean the country list first.

I would do it by retreving distinct country list and update the table for this column mannually( I mean separate updates). For example,

UPDATE mytableSET COUNTRY='USA'

WHERE Country='US'OR Country='U.S.'OR Country='United States'

These three USA names are from your sample data. This OR list will be long if you include all (mis)spellings you can find for the USA from your dirty data source.

After you have clean data, you can do something like this:

SELECT COUNTRY,count(COUNTRY)as cCount,(

CAST(count(COUNTRY)ASfloat)/CAST((SELECTcount(*)FROM countries$) ASfloat)*100)as countryPercent

FROM mytable

GROUPBY country

|||I figured the data would have to be cleaned... thanks for help with the second query, much appreciated... great help in this forum.