Showing posts with label alli. Show all posts
Showing posts with label alli. Show all posts

Wednesday, March 28, 2012

Help on SQL Injection...

Hi All:
I can't seem to get this thing work... When I type this in a textbox :'; exec master.dbo.sp_addsrvrolemember 'redice','sysadmin' -- , there's no respond, I mean, I check redice's role, but the System Administrators is not checked.
Any idea about this?
Thanks in advance.
Can you post your button click code or the code that executes the TextBox string?

|||Hi azamsharp:
This is my code:

Dim userNameAsString = txtUserName.Text

Dim pwdAsString = txtPwd.Text

Dim strSQLAsString = "select * from testing where userName = '" & userName & "' and pwd = '" & pwd & "'"

Dim comAsNew SqlCommand(strSQL, con)

Dim readerAs SqlDataReader

If pwd = ""Or userName = ""Then

lblMsg.Text = "Please enter user name and password."

Else

Try

con.Open()

reader = com.ExecuteReader

If reader.HasRowsThen

lblMsg.Text = "welcome"

Else

lblMsg.Text = "You are not authorized to enter this page."

EndIf

con.Close()

Catch exAs SqlException

lblMsg.Text = ex.Message

EndTry

EndIf
Thanks.

|||Guys, are you aware of how dangerous this can be? You are executing commands from web applications and that might cause you a lot of problems. I recommend you use parameters in your code while trying to access the SQL Server, this way everything entered in the textboxes would be treated as strings.
check this article please:UPDATE: Please, please, please, learn about injection attacks!
ergards
Regards|||First of all I have to agree with Bilal about SQL Injections. Don't runquery based on the parameters comming from the TextBoxes. Second yourcode looks fine to me, does it throw any exceptions. Are you authorizedto even run the select command on "testing" table. You can right clickthe table and give the users permission to run appropriate commands.Second It seems that all this code is written under "Button Click"event. If that is the case please keep all data access code in aseparate class library. Having code in Button Click means that you aremixing BLL with Presentation Layer.
Try to use stored procedures they are much faster than those queriesthat you are writing. Also check out the article below this may belittle advance for you but its always good to adopt good practices fromstart.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/CustEntCls.asp
|||

azamsharp wrote:

Try to use stored procedures they are much faster than those queries that you are writing.


I can prove that you are wrong over here. Stored procedures are just as fast in comparision to parameterized queries. There is, however, an exception to this finding under very certain circumstances but it is very rare that a stored procedure will outperform a parameterized SQL query by at least 5%. I'm just going to save me the time of what Frans Boumahas already done.

azamsharp wrote:

Don't run query based on the parameters comming from the TextBoxes.


You should parameterize anything that goes to your database. Instead of doing the bare minimum to protect from user input, you should do the full monty of parameterizing anything and everything you can. The reason is simply that you have not covered the full path of the exploit - you assume the most likely and yet are unable to cover the least expected. The truth of the matter is that is how exploits are found -- through the least expected resource.
If you trust drop down lists as being "secure," you better think twice. There is nothing stopping me from writing a HTTP request with a well crafted response of where your drop down lists is supposed to look like becoming my "text boxes." Another possible exploit is through querystrings. May I continue?
However, if you read the initial post clearly, it is not asking how to prevent SQL injections. It is merely trying to understand how SQL injections occur so value can be placed on how easy the exploit is. So it is not a matter of writing a well tiered application; it is just a demo to try understand the exploint.|||

redice wrote:

Hi All:
I can't seem to get this thing work... When I type this in a textbox :'; exec master.dbo.sp_addsrvrolemember 'redice','sysadmin' -- , there's no respond, I mean, I check redice's role, but the System Administrators is not checked.


To just put a simple example, here is some code:
command.CommandText = "select * from products where id = " + this.Page.QueryString["Id"];
As you guessed it, the above just gets the product out of the database based upon the ID passed in the querystring. Now the normal SQL that will yield for a URL like "View.aspx?Id=1" should be as follows:
select * from products where id = 1
Now let's assume we using the following URL:
View.aspx?Id=2; drop table products
Our favourite browser, Internet Explorer will automactially encode the URL for a proper URL request. The "SQL statement" that will be yielded is:
Select * from products where id = 2; drop table products
Which is actually two SQL statements! One being the "read" and the second part being the dropping of the table. Now is seems like that this was an easy attack. Let's try another ad-hoc SQL statement.
command.CommandText = "select * from products where productname = '%" + this.Page.Request.Querystring["SearchFor"] + "' order by price";
The first part of the SQL injection will be to insert the following into the builder:
'; select * from sysobjects where xtype = 'U
Now that will select all user objects from the database. And if you happen to display the exception information to the world, you just make the exploiters' lives easier because of obvious reasons. There may be other things that the exploiters' may use to find out more about your database... but if I tell you, I would have to kill youWink [;)]. However, there is your simple demo on how the SQL injections can occur.|||Hi all:
Okay, I know I should've said this. I was asked to do some experiments of how an attacker can use SQL Injection to attack the application. I KNOW how dangerous SQL Injection is. My bad, I guess, I should've mentioned to all of you that the purpose of this post is to find out how an attacker can attack... I was supposed to do a demo to my boss... Man~~~~ my bad, my bad...
Well, the user 'redice' has no permission at all, thus, this attacker (redice) is trying to grant himself a permissionsysadmin.
Anyone, please help.
Thanks.|||

redice wrote:

I should've mentioned to all of you that the purpose of this post is to find out how an attacker can attack... I was supposed to do a demo to my boss...

It is very good that you are cognisant of the risk of SQL injection attacks, and that you are trying to guard against them. You and your boss can pat each other on the back for your proactivity.
However, the above statement is a very risky approach to security. You should never presume to know how someone might attack your website. Unless you yourself are a very advanced hacker, then there is simplyno way to know how someone might attack your website. SQL injection attacks are only one type attack.

As Justin intimated, a hacker will not attack your website through your nicely crafted webpage. A hacker can use a spoofing program that allows him to create a complete HTTP request, adding any malicious form values, querystring values, and cookie values that he cares to add.If he's clever enough, and you haven't guarded against it, he can tamper with viewstate values to trigger a TextChanged event. [EDIT: By default, ViewState is tamper-proof.] The point is that you cannot "find out how an attacker can attack." You can learn some of the ways, and that's good, but it is the wrong approach to security in general.
What you need to do is assume that you simply don't know anything about how attackers do their thing, and instead follow well-documented best practices when designing your website. That is, you focus on your own defense, not on the attacker's offense.
Recently I conducted an audit of a website. I typed "goat's beard" into the search textbox, because that is the name of a flower, and is thus a legitimate search term. The apostrophe generated a server-side error that was echoed back onto the website. Sensing a vulnerability, I contacted a white-hat hacker. She quickly showed that the site was very vulnerable to SQL injection attacks.
I contacted the website's developer. Having been given this "demo"--precisely the type that you are creating for your boss--the website developer then updated his code to reject any search terms with an apostrophe. I pointed out that not only was that worthless, it means my dear old grandma cannot search for her favourite flower. In response, rather than reject such terms, he stripped out apostrophes from any query that went to the database. That too was worthless. This went on for a long time, as after fixing this single search textbox, he then had to do the same thing with the contact form's textboxes. The querystrings then proved to be vulnerable too.He was coding towards a demo of specific attacks, rather than coding a generalised defense.
This white-hat hacker was actually able to craft a querystring that permanently corrected a spelling mistake on the website. Had she been a black-hat hacker, who knows what she might have done.
The point of this story is that if you have a "demo", there is a real risk that you will code toknown attack types, updating your code until the demo suggests that your website is secure. The proper approach is to assume, quite correctly, that you simply cannot know all risks and all types of attack. This approach properly moves the focus to the defense, and not to the attacks.
Sheesh, another long reply. Perhaps my MVP award should read, "Most Verbose Person."

|||Hello fellows experts:
First of all, I wanna thank all of you for your inputs. It sure helps me to understand more bout SQL Injection. Ummm haha and after the miscommunication, SomeNewKid comes to my rescue. Thanks a lot. You've explained to me so detailed and yeah, you are so right about focusing the defense than the attack. Hope my demo will do fine.
Thank you to haidar_bilal, azamsharp, master4eva, and lastly, SomeNewKid! Thanks for sharing your thoughts.
CHEERS!
|||

Question to "Most Verbose Person"Smile [:)],
Is it possible to have some sort of a Blog entry or even an article, things that developers should take care of while developing website against attacks? For example, one of those threats are SQL Injection, Cross-Page scripting and others too. Explain each attack, and what is the proposed solution.
And comment on the ' stuff, parametrizing queries, doesn't overcome that problem of using ' ? just a question.
Regards

|||

haidar_bilal wrote:

Is it possible to have some sort of a Blog entry or even an article, things that developers should take care of while developing website against attacks?

The problem here is that there is not a single determinable setup that is entirely secure. As much as we may wish it were this simple, there cannot be some sort of checklist of attack types, and the defenses against them.
One of the greatest weaknesses in security is a developer whothinks his website is secure. A developer might follow an article of the type you suggest, implement its recommendations, and then consider the job is done. Hackers find new ways of attacking targets, and not all attacks are through software. There are social and physical aspects to hacking, too.
Even more telling, not all vulnerabilities are the domain of attackers. We developers can do dumb things and corrupt our own websites. Website owners or content providers may misuse their tools and inadvertently cause damage. Even Google has corrupted websites! (This occurs when the option to "delete this item" is a hyperlink rather than a true button, and Google happily follows that link as it indexes the site.)
All of this is compounded by the fact that websites grow and evolve, and so too do the technologies on which websites operate.
There are of course resources that talk about security. A pertinent one isBuilding Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication. This is a 600 page document of whichonly 3 pages deal with SQL injection attacks! You will see then that security is a mammoth topic that could never be covered in an article or a blog.
The point of my rambling is that security is such a huge topic that we must choose what it is that we focus on. The wrong thing to focus on is trying to learn all types of attacks and, one by one, address them. (Who'd have listed Google as an attacker?) The right thing to do is focus on the integrity of your code and the environment in which it executes.

Monday, March 19, 2012

Help needed with select query!

Hi All!

i have 2 tables

TABLE1
--
DESC
CODE
SEVERITY

CODE is the key here.
(SEVERITY ranges from 0 to 7)

TABLE2
--
CODE1
CODE2
CODE3
CODE4
CUST_ID
CALL_NBR

CUST_ID and CALL_NBR form the key.
CODE1 to CODE4 reference CODE in TABLE1

There can be at max 2 CALL_NBR per CUST_ID in TABLE2 i.e. at max 2
records per customer.

Now, what i need is

Extract 4 codes (CODE1, CODE2, CODE3, CODE4 frOM TABLE2...[remember,
there can be a max of 8 codes per customer]) into 4 variables per
customer based on priority defined in TABLE1This design definitely needs a rethink. The 4 Code columns are called a
repeating group and you should not have repeating groups in tables. There's
not really enough information to go on but I would expect a correctly
normalised design to look something like this:

CREATE TABLE CallCodes (descript VARCHAR(20) NOT NULL UNIQUE, code INTEGER
PRIMARY KEY, severity INTEGER NOT NULL CHECK (severity BETWEEN 0 AND 7))

CREATE TABLE CustomerCalls (cust_id INTEGER /* REFERENCES Customers
(cuist_id) */, call_nbr INTEGER, code INTEGER REFERENCES CallCodes (code),
PRIMARY KEY (cust_id, call_nbr, code) /* or (cust_id, call_nbr)? */)

Don't use Desc as a column name because it's a reserved word. When posting,
include DDL (CREATE TABLE statements, as above) with your posts so that it's
clear what the keys, constraints and data types are.

To find the 5 highest priority codes for each customer, assuming 7 is the
highest priority:

SELECT cust_id, code
FROM CustomerCalls AS A
WHERE code IN
(SELECT TOP 5 WITH TIES U.code
FROM CustomerCalls AS U
JOIN CallCodes AS O
ON U.code = O.code
WHERE U.cust_id = A.cust_id
ORDER BY O.severity DESC)

Note that if you had six codes for a customer with priorities 7,6,5,4,3,3
then this query will return all six codes, not five. You didn't specify what
you wanted to do if there were tied priorities so I've left them all in.

> Extract 4 codes (CODE1, CODE2, CODE3, CODE4 frOM TABLE2...[remember,
> there can be a max of 8 codes per customer]) into 4 variables per
> customer based on priority defined in TABLE1

Four variables per *customer*? You shouldn't need to do that in a relational
database. Please explain what you want to do and someone should be able to
suggest an alternative method.

--
David Portas
SQL Server MVP
--|||[Repost]
...

To find the 4 highest priority codes for each customer, assuming 7 is the
highest priority:

SELECT cust_id, code
FROM CustomerCalls AS A
WHERE code IN
(SELECT TOP 4 WITH TIES U.code
FROM CustomerCalls AS U
JOIN CallCodes AS O
ON U.code = O.code
WHERE U.cust_id = A.cust_id
ORDER BY O.severity DESC)

Note that if you had five codes for a customer with priorities 7,6,5,4,4
then this query will return all five codes, not four. You didn't specify
what you wanted to do if there were tied priorities so I've left them all
in.

> Extract 4 codes (CODE1, CODE2, CODE3, CODE4 frOM TABLE2...[remember,
> there can be a max of 8 codes per customer]) into 4 variables per
> customer based on priority defined in TABLE1

Four variables per *customer*? You shouldn't need to do that in a relational
database. Please explain what you want to do and someone should be able to
suggest an alternative method.

--
David Portas
SQL Server MVP
--|||Thanks for the response.

Well! I do understand that it is not a proper relational system but,
redesigning the table schemas is ruled out since it is a existing system
with lots of applications using it. The reason we have the 4 codes
stored per customer as different columns is coz we get these from an
external system based on many crietria,.

Here the DDLs of my 2 existing tables
CREATE TABLE [dbo].[MIX310] (
[REASON_CODE] [varchar] (2) NULL ,
[REASON_CODE_DESCRIPTION] [varchar] (80) NULL ,
[SEVERITY_CODE] [numeric](1, 0) NULL ,
[REASON_CODE_DESCRIPTION_SL] [varchar] (80) NULL
) ON [PRIMARY]
GO
note: SEVERITY ranges from 0 to 7

CREATE TABLE [dbo].[CUSTSWRESP] (
[CUST_ALT_ID] [varchar] (15) NOT NULL ,
[CALL_NBR] [numeric](1, 0) NOT NULL ,
[INPUT_MSG] [ntext] NULL ,
[MESSAGE_1] [varchar] (2) NULL ,
[MESSAGE_2] [varchar] (2) NULL ,
[MESSAGE_3] [varchar] (2) NULL ,
[MESSAGE_4] [varchar] (2) NULL ,
[SCORE] [varchar] (5) NULL ,
[RECOMMENDATION] [varchar] (2) NULL
(there are many other cols here...)
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[CUSTSWRESP] ADD
CONSTRAINT [PK_CUSTSWRESP] PRIMARY KEY CLUSTERED
(
[CUST_ALT_ID],
[CALL_NBR]
) ON [PRIMARY]
GO

Note: The only things of revelance in this case in CUSTSWRESP table are
the [CUST_ALT_ID], [MESSAGE_1],[MESSAGE_2],[MESSAGE_3] and [MESSAGE_4]
columns in our case.
Also, the MESSAGE_1...4 (message codes) refer to the REASON_CODE in
MIX310.

As I had earlier said, there can be at max 2 CALL_NBR for CUST_ALT_ID
i.e. at max 2 records per customer in CUSTSWRESP which implies have at
max 8 message codes. Also, all or just some of these message codes may
have values.

Now, i need to extract upto 4 REASON_CODE_DESCRIPTION from MIX310 based
on SEVERITY_CODE per CUST_ALT_ID where the message codes[MESSAGE_1...4]
in CUSTSWRESP match the REASON_CODE in MIX310.

I need urgent help with this. Please , let me know if there is any other
details needed.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||I'll assume that reason_code is unique in Mix310 even though that table
doesn't have a primary key (!).

CREATE VIEW CustomerMessages
(cust_alt_id, reason_code)
AS
SELECT cust_alt_id, message_1
FROM
(SELECT cust_alt_id, message_1
FROM Custswresp
UNION ALL
SELECT cust_alt_id, message_2
FROM Custswresp
UNION ALL
SELECT cust_alt_id, message_3
FROM Custswresp
UNION ALL
SELECT cust_alt_id, message_4
FROM Custswresp) AS M
WHERE message_1 IS NOT NULL

SELECT cust_alt_id, reason_code
FROM CustomerMessages AS T
WHERE reason_code IN
(SELECT TOP 4 WITH TIES C.reason_code
FROM CustomerMessages AS C
JOIN Mix310 AS M
ON C.reason_code = M.reason_code
WHERE C.cust_alt_id = T.cust_alt_id
ORDER BY M.severity_code DESC)

--
David Portas
SQL Server MVP
--|||Hi David!

Thanks for the quick response.

I could get it working and it gives the desired outcome.

I'll most probably twist it a little to use a #temp table instead of a
view since i m using it inside a stored procdure which recieves
cust_alt_id as input parameter.

I'll repost it when i m done for your comments since i m still a sql
novice.

Thanks!

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||If you just wanted to return a result for a single customer at a time you
can do this:

SELECT TOP 4 WITH TIES M.reason_code, M.reason_code_description
FROM
(SELECT cust_alt_id, message_1
FROM Custswresp
UNION ALL
SELECT cust_alt_id, message_2
FROM Custswresp
UNION ALL
SELECT cust_alt_id, message_3
FROM Custswresp
UNION ALL
SELECT cust_alt_id, message_4
FROM Custswresp) AS
C (cust_alt_id,reason_code)
JOIN Mix310 AS M
ON C.reason_code = M.reason_code
WHERE C.cust_alt_id = @.cust_alt_id
ORDER BY M.severity_code DESC

--
David Portas
SQL Server MVP
--|||O! thatz a great help!!

I had atually started going the temp table way...

A lil more help...this returns me the top 4 reason codes descriptions.
Now, what i need (and what i apoligize for not having elaborated
earlier) is to assign these to 4 to local variables within the procedure
since i need them for some other processing and also return them to the
component which is invoking the stored procedure.

I need something like...
SELECT @.EmpiricaFirstFactor = ISNULL(REASON_CODE_DESCRIPTION,'')
SELECT @.EmpiricaSecondFactor = ISNULL(REASON_CODE_DESCRIPTION,'')...and
so on.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Rather than assign four variables and then manipulate them further, try to
extend my query to produce the end result you require and then return that
result set from the stored procedure. In general you should try to keep
step-by-step procedural processing to a minimum in SQL.

One problem with your specification is the handling of tied values. If you
have only four variables but you have five different reason_codes with
severities 7,6,5,4,4 , which values of reason_code_description do you want
to return? The two values with severity 4 might have different descriptions
but you only want to return one of them. At least add reason_code into the
ORDER BY clause so that you get a consistent (but not necessarily useful)
result in that case:
...
ORDER BY M.severity_code DESC, C.reason_code

If you must assign four variables in your SP then you can try the following.
However this is a rather questionable, undocumented and possibly not 100%
reliable method of doing this. I strongly recommend that you return the
values as a result set instead.

DECLARE @.empirica1 VARCHAR(80), @.empirica2 VARCHAR(80), @.empirica3
VARCHAR(80), @.empirica4 VARCHAR(80)

SELECT TOP 4
@.empirica1 = @.empirica2,
@.empirica2 = @.empirica3,
@.empirica3 = @.empirica4,
@.empirica4 = M.reason_code_description
FROM
...

--
David Portas
SQL Server MVP
--|||>> I do understand that it is not a proper relational system but,
redesigning the table schemas is ruled out since it is a existing
system with lots of applications using it. <<

LOL! Everytime I read "redesigning the schema is not allowed", I keep
thinking that: (1) This guy has decided that bankruptcy and total
failure ARE allowed! (2) I'm going to get a consulting job with a huge
daily rate in about a year

If this is true, then the application and the backend have been
coupled together much, much too tightly.

>> the reason we have the four codes stored per customer as different
columns is because we get these FROM an external system based on many
criteria. <<

Unh?? That has absolutely nothing to do with how the database stores
the facts. Quit mimicking a physical file layout.

>> here the DDLs of my two existing tables <<

MIX310 is not a table and it can never be a table. There are no keys
and with the NULL-able columns,there can never be a key. You failed
to put in a known constraint on the table. Your datatypes are wrong
-- VARCHAR(2) is a bitch for the front end guys who have to pad it out
to print it; use CHAR(n) for short codes.

You talk about joining on reason codes, but have no such column in
CUSTSWRESP. Did you actually give the same data element mulitple names
in the schema? Do you have not DRI between the tables?

This is such a mess you need to start over.

CREATE TABLE MIX310
(reason_code CHAR(2) NOT NULL PRIMARY KEY,
reason_description VARCHAR (80) NOT NULL, -- punch card width!
severity_code INTEGER NOT NULL -- code description in another table?
CHECK (severity BETWEEN 0 AND 7),
);

>> .. Which implies have at most 8 message codes. <<

So design a table something like this:

CREATE TABLE CustMessages
(cust_id VARCHAR (15) NOT NULL
REFERENCES Customers (cust_id)
ON UPDATE CASCADE,
message_nbr INTEGER DEFAULT (1) NOT NULL
CHECK (message_nbr BETWEEN 1 AND 8), -- enforce business
rule
message_txt TEXT NOT NULL,
reason_code CHAR(2) NOT NULL
REFERENCES MIX310 (reason_code)
ON UPDATE CASCADE,
...
PRIMARY KEY (cust_id, call_nbr));

Now use "message_nbr BETWEEN 1 and 4" to get that sample. Ordering the
messages by severity is a simple update.

Right now, you have no data integrity in the current schema. All your
queries will convoluted nightmares that produce erroneous results. If
you cannot fix it, you might want to update your resume and try to
find a company that will be in business.

Wednesday, March 7, 2012

Help needed

Hi all

I m having three tables youth,clubs,ythclubs. youth may participate in any no of clubs.
in youth youth_id is the key attribute. In clubs club_id is the key attribute.Table ythclubs consists the columns youth_id,club_id. My requirement is
If user selects a club, it should give the list of youths in that club along with the some columns of youth(for ex lastname,firstname like this)

Sample data is
This is in Youths table This is in clubs table
Youthid club_id
10005 10003
10006 10004
10007 10005
10008 10000

In ythclub the data is
club_id youthid
10005 10005
10003 10005
10004 10005
10006 10006
10005 10012
10006 10012

Thank u

Baba

It sounds to me like you should be able to do this with a select that joins the Youth and ythclub tables:

Code Snippet

declare @.Youth table
( YouthId integer,
lastName varchar(12),
firstName varchar(12)
)
insert into @.Youth
select 10005, 'Rubble', 'Fred' union all
select 10006, 'Flintstone', 'George' union all
select 10007, 'Jetson', 'Barney' union all
select 10008, 'Douglas', 'Jed' union all
select 10012, 'Kiley', 'Oliver'
--select * from @.youth

declare @.ythClub table
( club_id integer,
youthId integer
)
insert into @.ythClub
select 10005, 10005 union all
select 10003, 10005 union all
select 10004, 10005 union all
select 10006, 10006 union all
select 10005, 10012 union all
select 10006, 10012
--select * from @.ythClub

declare @.targetClub integer
set @.targetClub = 10005

select a.club_id,
a.youthId,
b.lastName,
b.firstName
from @.ythClub a
join @.Youth b
on a.youthId = b.youthId
and a.club_id = @.targetClub
order by b.lastName, b.firstName

/*
club_id youthId lastName firstName
-- --
10005 10012 Kiley Oliver
10005 10005 Rubble Fred
*/

If you need anything from the CLUB table -- such as the name of the club -- then you will also need to join to the CLUB table.

Help needed

Hello to all
I need help on some sql statements and wondering is anyone out there is able
to help.
I've extracted some data from the database into a new table consisting of 4
fields

CustomerID Date Pallets Quantity
A0001 20050108 3 800
A0001 20050111 -2 -300
A0001 20050203 8 1200
A0001 20050212 -3 -500

my requirements:
1. to convert the date format from 20050118 to 18-Jan-2005
2. To have an option for selection by customer and date range :-
Selected Customer : A0001
Date Range : 01-Feb-2005 to 12-Feb-2005
3. the result to be display :-

CustomerID Date RunningPallet# RunningTotalQty
A0001 01-Feb-2005 1
500
A0001 03-Feb-2005 9
1,700
A0001 12-Feb-2005 6
1,200

hope someone can help me out on this as i am not an sql user

TQ"-" <niteking@.hotmail.com> wrote in message
news:4219a0af$1_2@.news.tm.net.my...
> Hello to all
> I need help on some sql statements and wondering is anyone out there is
> able to help.
> I've extracted some data from the database into a new table consisting of
> 4 fields
> CustomerID Date Pallets Quantity
> A0001 20050108 3 800
> A0001 20050111 -2 -300
> A0001 20050203 8 1200
> A0001 20050212 -3 -500
> my requirements:
> 1. to convert the date format from 20050118 to 18-Jan-2005
> 2. To have an option for selection by customer and date range :-
> Selected Customer : A0001
> Date Range : 01-Feb-2005 to 12-Feb-2005
> 3. the result to be display :-
> CustomerID Date RunningPallet# RunningTotalQty
> A0001 01-Feb-2005 1 500
> A0001 03-Feb-2005 9 1,700
> A0001 12-Feb-2005 6 1,200
> hope someone can help me out on this as i am not an sql user
> TQ

1. You should format the date in your client application, not in MSSQL. But
if you really want to do it on the server side, have a look at the CONVERT()
function in Books Online.

2. MSSQL is a server, and it has no concept of interfaces, prompts, menus
etc. To allow a user to select their own criteria, you would need to build
some sort of front end, in whatever your preferred tool/language is -
Access, ASP, C# etc. The criteria that the user selects should probably be
used as parameters to a stored procedure (see below).

3. You can use a query or stored procedure as shown below (not fully
tested). In some cases, you might find it easier to do running totals in the
front end when you present the data; you could also consider using a
reporting tool for more complex work.

If this doesn't help, or if you get unexpected results, I suggest you post
CREATE TABLE and INSERT statements to set up a test case:

http://www.aspfaq.com/etiquette.asp?id=5006

Simon

/* As a query */
select
CustomerID,
'20050201' as 'Date',
sum(Pallets) as 'Pallets',
sum(Quantity) as 'Quantity'
from
dbo.MyTable
where
[Date] < '20050202'
group by
CustomerID
union all
select
t1.CustomerID,
t1.[Date],
sum(t2.Pallets),
sum(t2.Quantity)
from
dbo.MyTable t1 join dbo.MyTable t2
on t1.CustomerID = t2.CustomerID
and t1.[Date] >= t2.[Date]
where
t1.CustomerID = 'A0001' and
t1.[Date] >='20050201' and
t1.[Date] < '20050213'
group by
t1.CustomerID,
t1.[Date]
order by
Date

/* As a proc */
create proc dbo.getTotals
@.CustomerID char(5),
@.StartDate datetime,
@.EndDate datetime
as
set nocount on
begin

select
CustomerID,
@.StartDate as 'Date',
sum(Pallets) as 'Pallets',
sum(Quantity) as 'Quantity'
from
dbo.MyTable
where
[Date] < dateadd(dd, 1, @.StartDate)
group by
CustomerID
union all
select
t1.CustomerID,
t1.[Date],
sum(t2.Pallets),
sum(t2.Quantity)
from
dbo.MyTable t1 join dbo.MyTable t2
on t1.CustomerID = t2.CustomerID
and t1.[Date] >= t2.[Date]
where
t1.CustomerID = @.CustomerID and
t1.[Date] >= @.StartDate and
t1.[Date] < @.EndDate
group by
t1.CustomerID,
t1.[Date]
order by
Date

end|||On Mon, 21 Feb 2005 16:48:39 +0800, - wrote:

>Hello to all
>I need help on some sql statements and wondering is anyone out there is able
>to help.
>I've extracted some data from the database into a new table consisting of 4
>fields

Hi TQ,

Is there any specific reason why you made a new table with a subset of the
data in the database? Since you are introducing redundancy, you now run
the risk of corrupting data integrity. And you might possibly be degrading
performance as well.

>CustomerID Date Pallets Quantity
>A0001 20050108 3 800
>A0001 20050111 -2 -300
>A0001 20050203 8 1200
>A0001 20050212 -3 -500

Date is a reserved word in MS SQL Server. I suggest you to choose another
column name.

>my requirements:
>1. to convert the date format from 20050118 to 18-Jan-2005

I assume that you have defined Date as a column of datatype datetime or
smalldatetime. In that case, the date representation in internal storage
is unlike anything you or I would recognise as a date. How you see it is
decided by the client software you're using. Even Query Analyzer and
Enterprise Manager (both by MS, both part of the SQL Server package) use
different formats to display dates.

If the column Date is not defined as [small]datetime, then you have a much
bigger problem - I suggest you fix that first before attempting to execute
any query that uses the dates for calculations, selections, ordering or
whatever.

>2. To have an option for selection by customer and date range :-
> Selected Customer : A0001
> Date Range : 01-Feb-2005 to 12-Feb-2005
>3. the result to be display :-
> CustomerID Date RunningPallet# RunningTotalQty
> A0001 01-Feb-2005 1
>500
> A0001 03-Feb-2005 9
>1,700
> A0001 12-Feb-2005 6
>1,200

-- Check the datatypes below and change them to match
-- the datatype of the columns CustomerID and Date.
DECLARE @.CustID char(5)
DECLARE @.StartDate smalldatetime
DECLARE @.EndDate smalldatetime
SET @.CustID = 'A00001'
SET @.StartDate = '20050201'-- Always use yyyymmdd for date literals
SET @.EndDate = '20050212'

SELECT a.CustomerID, a."Date",
COALESCE(SUM(b.Pallets),0) AS RunningPallet#,
COALESCE(SUM(b.Quantity),0) AS RunningTotalQty
FROM (SELECT CustomerID, Date
FROM MyTable
WHERE CustomerID = @.CustID
AND "Date" >= @.StartDate
AND "Date" <= @.EndDate
UNION
SELECT @.CustomerID, @.StartDate) AS a
LEFT OUTER JOIN MyTable AS b
ON b.CustomerID = a.CustomerID
AND b."Date" <= a.Date
GROUP BY a.CustomerID, a."Date"

(untested - post CREATE TABLE and INSERT statements in your question to
get tested results. See www.aspfaq.com/5006)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo Kornelis (hugo@.pe_NO_rFact.in_SPAM_fo) writes:
> Date is a reserved word in MS SQL Server. I suggest you to choose another
> column name.

Date may show up in different colour in Query Analyzer, but it's certainly
not a reserved keyword:

CREATE TABLE date(date datetime NOT NULL)
The command(s) completed successfully.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Books Online lists DATE under the Future Keywords section ("could be
reserved in future releases") and as an ODBC Reserved Keyword
("applications should avoid using these keywords"). DATE is also a
reserved word in ANSI/ISO Standard SQL.

However, the most important reason not to use the word DATE as a column
name, is that it's such a vague and uninformative name.

--
David Portas
SQL Server MVP
--|||David Portas (REMOVE_BEFORE_REPLYING_dportas@.acm.org) writes:
> Books Online lists DATE under the Future Keywords section ("could be
> reserved in future releases") and as an ODBC Reserved Keyword
> ("applications should avoid using these keywords"). DATE is also a
> reserved word in ANSI/ISO Standard SQL.

As a datatype name, I guess? Datatypes are not reserved keywords in T-SQL,
they are just unreserved keywords:

CREATE TABLE confuse (int char(2) NOT NULL,
timestamp decimal(8,2) NOT NULL,
datetime int NOT NULL,
money uniqueidentifier NOT NULL)

The are not case-sensitive in case-sensitive databases through.

> However, the most important reason not to use the word DATE as a column
> name, is that it's such a vague and uninformative name.

True.

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

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