|
unless you are selecting from a view which is used in several places, and an update to one place requires a change to the view, you could break anywhere where you used select *, but select col1, col2, col3 wont break as long as those columns are still present in the view. it not only needs to work well now it needs to work well in the future and not cause unnecessary problems for other people who may be doing updates, and not know all sections of a project like the person who first wrote them. Good practices will protect you from a lot including security threats, doubling tick marks ' to '', removing special characters, and validating your user's input will prevent more problems than i can count including sql injection, and it doesnt take much longer to write. sorry for getting off topic.
|
|
|
|
|
SELECT col1, col2, col3 will break just as easy as SELECT * if you remove the columns your query depends on.
It has nothing to do with SELECT * or not.
SELECT * is bad if you move (way) more data then you need. It is needless to do. But if you need all - or almost all - the data, it is fine.
|
|
|
|
|
Using parameterized stored procedures should cover you against the most direct forms of SQL Injection attack, unless you use string execution like:
EXEC ('SELECT * FROM MYTABLE WHERE ID = ' @INPUTSTRING)
In that case, validate input and replace ' with '' and do not allow the keywords which could do harm.
Generally - it is a bad thing to take user input and run it directly in a query, but as said - if you use parameterized SPROCs you should be pretty safe to begin with.
|
|
|
|
|
Actually I am trying to implementa function which can restrict or blacklist some database syntaxes like select, sys, insert etc. and do not allow them to fire i.e. to check input ...
But yet I m not entirely successful in that...
No idea how to implement that I just thought this thing yet...
|
|
|
|
|
Hi!
Let's say this is an old web site built in ASP with VBScript and it's just had an SQL Injection attack (as happened to me a week ago - I have hundreds of old sites running, and sometimes I or a colleague have had a bad day years ago - it tends to come back and bite you). You've stopped the web, cleaned the database (let's say it only appended script tags to some text fields, so it was a quick fix - this is common bot behaviour).
Quick and dirty fix to get it up:
Search for the word "WHERE" in the site source. Replace this:
Recs.Open "SELECT ... FROM ... WHERE x = '" & something & "' ..." ...
with:
Recs.Open "SELECT ... FROM ... WHERE x = '" & Replace(something, "'", "''") & "' ..." ...
and this:
Recs.Open "SELECT ... FROM ... WHERE someid = " & something & " ...", ...
with:
Recs.Open "SELECT ... FROM ... WHERE someid = " & CLng(something) & " ...", ...
'CLng will throw on invalid input!
This is a naive fix and only stops the most common attacks. So... when the site is up, you spend the next day rewriting further (from memory, possibly lots of syntax errors and remembering things wrong, but the concept is correct):
Set cmd = Server.CreateObject("ADODB.Command")
cmd.CommandText = "SELECT ... FROM ... WHERE x = ? ..."
cmd.Parameters.Add cmd.CreateParameter("@p1", ...)
Recs.Open cmd, ...
And yes, you'd want to wrap that in a function, like so:
Recs.Open SqlCmd("SELECT...", Array(param1, param2)), ...
(the hideous Array() construct is because VBScript doesn't know about parameter arrays - also beware that you must analyze the values to figure out the proper types and other parameter metadata in the SqlCmd function)
If you're using .Net, look at the SqlCommand (or DbCommand) object. Same thing. There are several reasons to use parameterized queries:
- SQL Server can cache execution plans for similar queries - this improves performance A LOT if you do the same query over and over with different parameters.
- You're immune to SQL Injection attacks.
- You're code gets easier to read (provided you encapsulate the mechanism properly, otherwise it will bloat the code).
Then again, why don't we just round up all hackers and shoot them? I could even consider molesting them for a while first...
Peter the small turnip
(1) It Has To Work. --RFC 1925[^]
|
|
|
|
|
Currently i m using sql server 2000. when i directly modify the values inside the database the following TRIGGER fires correctly. But when pass values from front end (ASP.NET with C#, .net 2005, 2.0 framework) "update tbl_ORA_TBOps set Percentage_Compliant=((@comp/@tot_ex)*100) where AutoID=@id" this alone not working.. what problem.....? plz..
CREATE TRIGGER [calc] ON dbo.tbl_ORA_TBOps
AFTER INSERT, UPDATE
AS
begin
update tbl_ORA_TBOps set Total=(Compliant+Non_Compliant+InProgress+InputNotReceived+NA)
update tbl_ORA_TBOps set Total_Excl_NA=Total-NA
end
begin
declare @tot numeric
declare @na numeric
declare @tot_ex numeric
declare @comp numeric
declare @id numeric
select @tot=(Select total from inserted)
select @na=(Select NA from inserted)
select @tot_ex=(Select Total_Excl_NA from inserted)
select @comp=(Select Compliant from inserted)
select @id=(Select AutoID from inserted)
if (@tot=@na)
begin
update tbl_ORA_TBOps set Percentage_Compliant=100 where AutoID=@id
end
else
if (@tot_ex=0)
begin
update tbl_ORA_TBOps set Percentage_Compliant=0 where AutoID=@id
end
else
begin
update tbl_ORA_TBOps set Percentage_Compliant=((@comp/@tot_ex)*100) where AutoID=@id
end
end
in the above trigger, i m getting incorrect Percentage_Compliant value. how to solve this (i m very beginner to TRIGGERS). is the IF...ELSE loop correct? HELP ME! - KARAN
modified on Thursday, May 29, 2008 8:38 AM
|
|
|
|
|
Without looking in detail at your code, here is one critical heads-up about triggers: The inserted and deleted virtual tables contain more than one row. If you run one update statement that affects ten rows, they will contain ten rows each. The trigger gets called once per update statement, not once per row! Similar for all types of triggers.
So... your set @variable = (select ... from ...) would not do at all what you expect it to.
Rethink your approach accordingly.
Peter the small turnip
(1) It Has To Work. --RFC 1925[^]
|
|
|
|
|
Thanks peter.... I m a beginner to TRIGGERS. so i will rectify my errors. but the thing is here... the ELSE part alone is not working.... other if loops working fine..... could u guide me to proceed this process? when i try the same in C#.NET the loop is working fine...
help me!
thanks for understanding....
|
|
|
|
|
I'm not sure I understand your question. When you're saying loop, what do you mean? You usually don't do work using loops in SQL, as SQL works on sets, not items. With sets, you specify a statement that says what should be done with the entire set. With items (as in C# or another procedural language) you loop over all the elements and do something to them one at a time. These are different ways of thinking altogether, and you can't mix the two.
So, instead of (abstract example, has nothing to do with your sample as I don't understand it, but the thinking should be similar):
-- The following wont work at all if inserted contains
-- more than one row (which it will if the statement
-- firing the trigger affects more than one row):
set @x = (select x from inserted)
if @x = 10 then set @y = 20 else set @y = 30
update target set y = @y
you do something like this:
update target set y = (case x when 10 then 20 else 30 end)
where target.id in (select id from inserted)
Note: There is an example that looks like yours in SQL Server Books Online, but like yours, it will fail when an update or insert statement affects more than one row.
I can't elaborate much on this without writing a small book, but what you have to realize is that with SQL you have to think quite differently than in procedural languages.
Peter the small turnip
(1) It Has To Work. --RFC 1925[^]
|
|
|
|
|
|
I want to know where all a particular tables primary key is used as foriegn key in the database. Is there any built in stored procedure for that?
|
|
|
|
|
You haven't provided the database version you're using then you can look up "Information Schema Views" in BOL. The following query makes use of the information schema which is SQL-92 compliant and should work with any database engine which is also SQL-92 compliant, not just SQL Server:
<br />
<br />
SELECT P.TABLE_NAME AS ParentTable, P.CONSTRAINT_NAME AS PrimaryKey, FK.TABLE_NAME AS ChildTable, FK.CONSTRAINT_NAME AS ForeignKey <br />
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS P<br />
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC ON RC.UNIQUE_CONSTRAINT_NAME = P.CONSTRAINT_NAME<br />
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON FK.CONSTRAINT_NAME = RC.CONSTRAINT_NAME<br />
WHERE P.CONSTRAINT_TYPE = 'PRIMARY KEY'<br />
ORDER BY ParentTable, ChildTable<br />
<br />
|
|
|
|
|
Hi to all
i want to copy entire data from one of my table to that of another
table. source table is created and having 1000 of rows and
destination table is not created this i want to do in a single statment.
Thanks in advance.
|
|
|
|
|
soniasan wrote: i want to copy entire data from one of my table to that of another
table. source table is created and having 1000 of rows and
destination table is not created this i want to do in a single statment.
You will need to look up the SELECT INTO SQL statement.
|
|
|
|
|
Be warned, if there are large volumes of data using the SELECT INTO method could lock all other processes out as it locks the system tables (such as syscolumns, sysobjects etc) for the duration of the select.
It is much better to do it in two steps:
SELECT * INTO new_table FROM old_table WHERE 1 = 2 -- creates the new table
INSERT INTO new_table SELECT * FROM old_table -- populate it
Bob
Ashfield Consultants Ltd
|
|
|
|
|
So flame me for asking something which is probably Google-able, but I couldn't find it!
What is the maximum string-length that can be output using the PRINT command in SQL 2005?
E.G
<br />
DECLARE @myString Varchar(max)<br />
<br />
SET @myString = 'Imagine a very looooooooong string here!'<br />
<br />
PRINT @myString
|
|
|
|
|
It was easy to find out - 8000
declare @a varchar(max)
select @a = replicate('a',7999) + 'b'
print @a
--prints 7999 a's and a b
select @a = replicate('x',8000) + 't'
print @a
--prints 8000 x's but no t
Bob
Ashfield Consultants Ltd
|
|
|
|
|
I'm trying to insert a lot of data (10 million records) to my oracle server,
my original plan works but it's very slow
I’m using OracleDataAdapter with UpdateBatchSize = 100
if I’m setting this value to more than that I’m receiving oracle exception saying:
my software is to big (it compiles it to a huge StoredProcedure and send it to the oracle server)
so my question is, what can be done to speed things up?
Thanks in advance,
Yaron
|
|
|
|
|
Hie
I am new to sql 05, and am buiding a windows app for a hotel. I would like to to retrieve the number of occupants in the various types of rooms on a between a specified date range. eg from the 1st of the month to the end of the month.
For each day in the specified range I would like to retrieve the number occupants in each type of room. I have been able to do this by generating a different select statement for each day that is automatically updated by the program. I however feel that this method is very inefficient and would like to use a single sql statement to pull the data from the database and place it into a datatset.
Does anyone have any idea on hw i cld get around this. thank u.
tw5ted f8
|
|
|
|
|
Your query looks like:
select count(occupants) from tablename<br />
group by [datecol],roomtype<br />
having datecol between '2008-05-01' and '2008-05-31'
If this doesn't helps you then post data as they are saved in table and post output result which u want to have, we will see what we can do.
I Love T-SQL
"Don't torture yourself,let the life to do it for you."
|
|
|
|
|
Hello,
I'm trying to connect to an Access database using C# Asp.NET 3.5. Although i'm setting the connection and the connection is opening successfully, when trying to execute a command against a table Visual Studio throws the following error:
OleDbException
"Could not find file 'C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\CCureLiveData.mdb'."
The connection string has not changed and the database is open, it is just the command that is causing this error for some reason!
Does anybody know why VS looks in the directory in the first place? I have not told it to and all the right permissions are set on the folder where it should be looking!
Any help would be very much appreciated!
Thanks Matthew Chamberlain
|
|
|
|
|
For best results in all Windows file handling, always specify the full path to any file. Otherwise you get the 'current directory', which is potentially different for each thread (a thread inherits its 'current directory' from the process, if I recall correctly).
For ASP.NET consider using Server.MapPath to find a file. Use ~/ notation (e.g. "~/CCureLiveData.mdb") to find a file relative to the current application's root - this is easier, and will work even on medium-trust web servers.
DoEvents: Generating unexpected recursion since 1991
|
|
|
|
|
Hi all,
i had one datalist which appear all the pros for all the cities in the links of blue color.
but i need to display the link color in red to those pro who r working for us. i add one column in database 'workus' a bit. if 'workus' is true then it will display in red color.else in blue color.
Protected Sub dtlstPros_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs)
Dim objAnchor As HtmlAnchor
Dim drRow As DataRow
Dim proCurrenctCityID As Int32 = 0
Dim proPrevCityID As Int32 = 0
Dim intRecCount As Int16 = 0
If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
drRow = CType(CType(e.Item.DataItem, DataRowView).Row, DataRow)
proCurrenctCityID = CType(drRow("CityID"), Int32)
If ViewState("PrevCityID") <> proCurrenctCityID Then
ViewState("PrevCityID") = proCurrenctCityID
ViewState("Count") = 0
End If
'If ViewState("RecCount") < DISP_NOOF_PROS Then
''Workaround for hard links
Dim strRedirection As String = ""
Dim strFormatCompanyName As String = ""
Dim intLen As Int16 = 0
***********workus = Convert.ToBoolean(drRow("workus "))
If zoompro = True Then
objAnchor = CType(e.Item.FindControl("ancPro"), HtmlAnchor)
objAnchor.Style.Add("cssClass", "text12red")
'objAnchor.Style.Add("style", "*")
Else
objAnchor = CType(e.Item.FindControl("ancPro"), HtmlAnchor)
End If***************
objAnchor = CType(e.Item.FindControl("ancPro"), HtmlAnchor)
strRedirection = String.Format("~/xyz/Details.aspx?ID= {0}&CName={1}&CName={2}&ID={3}&Page={4}", drRow(Cas.GUID).ToString, drRow(cas.CNAME).ToString, Request.QueryString("Name"), Request.QueryString("ID"), "City")
objAnchor.HRef = strRedirection
intLen = drRow("CName").ToString.Length
If intLen > PNAME_LENGTH Then
strFormatCompanyName = Mid(drRow("CName").ToString, 1, PNAME_LENGTH)
objAnchor.InnerText = strFormatCompanyName + "..."
Else
objAnchor.InnerText = drRow("CName").ToString
End If
''End Workaround for hard links
'End If
ViewState("Count") += 1
End If
End Sub
can any one help me how to change the color of 'anctag' to red if workus=true
Thanks in advance
Thanks
Subbu.
|
|
|
|
|
Hi,
I dont know if this is possible, but I'll ask anyway.
I need to be able to send an SQL script as a text file, or something similar. The script will be modifying a few columns, and inserting a few new rows. Nothing too complictated....
However...
I am using SqlCE 3.5, so the commandset is slightly reduced, and, worst of all, one of the fields is an Image (i.e. Binary). Its not huge, most records are about 1k, however, it has thrown a bit of a spanner in the works for my simple script idea.
So, I guess I am asking, is there a reasonably simple way to script a database which contains binary data?
Thanks,
Jason
|
|
|
|
|
Replying to my own question... I must be sad )
Anyway, it was easy... after a lot of googling:
insert into [Table] (Field) Values (0x1232132132)
I am a bit ashamed that I missed that. Posted here in case someone else needed it.
|
|
|
|
|