I've used this script by accident on the 'master' database instead of a temp database.
sp_msforeachtable 'delete from ?'
Has it caused any harm? If so, how can I restore the data?
No it shouldn't have deleted anything (assuming you have no user tables in master).
Testing
exec sys.sp_MSforeachtable 'select ''?'''
Doesn't return anything for me. So it seems to exclude the system tables such as spt_values.
Edit: Indeed Looking at the definition of the procedure it does only include tables where OBJECTPROPERTY(o.id, N'IsUserTable') = 1
Martin Smith is right to say that sp_MSforeachtable does not delete system tables.
However, though we may think of tables such as spt_values and MSreplication_options as system tables, they are in fact user tables according to SQL Server.
When I run this query in my master database:
SELECT name, OBJECTPROPERTY(object_id, N'IsUserTable') AS IsUserTable
FROM master.sys.tables;
I see the following result set:
name IsUserTable
--------------------- -----------
spt_fallback_db 1
spt_fallback_dev 1
spt_fallback_usg 1
spt_monitor 1
MSreplication_options 1
So how was Stijn saved from a reinstall?
If you look at how sp_MSforeachtable is implemented, you will see it does something like this to select the tables to drop:
declare #mscat nvarchar(12)
select #mscat = ltrim(str(convert(int, 0x0002)))
SELECT *
from dbo.sysobjects o join sys.all_objects syso on o.id = syso.object_id
where OBJECTPROPERTY(o.id, N'IsUserTable') = 1 and o.category & #mscat = 0;
In my master database, this returns an empty result set.
The where clause applies a bitmask to the category column of table sysobjects to exclude tables that are not 'mscat'.
So the tables in the master database are protected not because they are system tables, but because they are 'Microsoft' tables.
This use of the category column is completely undocumented in Books Online All it has is a vague description:
Used for publication, constraints, and identity.
But the sysobjects table is deprecated anyway, so you shouldn't be using it. :)
An equivalent query using the supported view sys.tables would look like this:
SELECT *
FROM sys.tables
WHERE is_ms_shipped = 0;
In my master database, this also returns an empty result set.
Related
I'm working with mySQL db and trying to display the correct data for the user. In order to do that I check if the data that I call from one backend is equal to username from another backend like so
SELECT * FROM db1 WHERE db1.table.value = db2.table.value
Names of databases are A and B.
SELECT *
FROM `A.onboardings`
, `B.loginsystem`
WHERE onboardings.sales_email = loginsystem.username
The problem is I get an error A.A.onboardings doesn't exists and A.B.loginsystem doesn't exist pls help :(
You must use this form - from A onboardings
You have to put the backticks in the right pace, or else mysql things your table is called A.onboardings
As seen bleow the needs to be around the database and the table name
And the use of aliases helps to keep even in big queries a good overview and yu have to write less
"SELECT * FROM `A`.`onboardings` a1,`B`.`loginsystem` b1 WHERE a1.sales_email = b1.username"
Try this one( Change the query according to your DB name, table, and matching column name)
SELECT * FROM mydatabase1.tblUsers INNER JOIN mydatabase2.tblUsers ON mydatabase1.tblUsers.UserID = mydatabase2.tblUsers.UserID
The problem is that
`A.onboardings`
is not the same as
A.onboardings
The first is a table reference where there table name has a period in it. The second is for the onboardings table in database A.
In addition, you should be using JOIN!!!
SELECT *
FROM A.onboardings o JOIN
B.loginsystem ls
ON o.sales_email = ls.username;
If you feel compelled to escape the identifies -- which I do not recommend -- then:
SELECT *
FROM `A`.`onboardings` o JOIN
`B`.`loginsystem` ls
ON o.sales_email = ls.username;
I am still very new to SQL. I am working on a system which uses Derby database in development and Oracle in production. I want to have an SQL Statement which works in both. Here is my code:
SELECT rma.crspdt AS bic_crspndt,
rma.issr AS bic_issr
FROM rma
WHERE (rma.tp = 'Issued' OR rma.tp = 'Received')
AND rma.rmasts = 'Enabled'
AND rma.svcnm = 'swift.fin') r
INNER JOIN (SELECT 1 ID FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 2 ID FROM SYSIBM.SYSDUMMY1) dummy ON (dummy.id = 1 AND r.bic_crspndt IS NOT NULL)
OR (dummy.id = 2 AND r.bic_issr IS NOT NULL)
I am using here 'SYSIBM.SYSDUMM1' table. Oracle has an exact alternative table for 'SYSIBM.SYSDUMM1' named 'DUAL'. The problem is that when I run my code in development (derby) this code works fine but in production (oracle) I get an error saying something like unknown table.
What I want to do is that in my code do an IF-ELSE/CASE-WHEN or something like this to check in runtime if 'SYSIBM.SYSDUMMY1' table exists and if it does not exist (like in oracle) then I want to use 'DUAL' table. I am very new to SQL and would like some help in this matter.
You don't say which Oracle version you are using. In Oracle 12c there is the SQL Translation Framework.
With this example you could set up a translation such that SYSIBM.SYSDUMMY1 is translated to DUAL.
I've seen demonstrations but haven't used it personally. I suggest the Oracle docs (as usual) for information - https://docs.oracle.com/database/121/DRDAA/sql_transl_arch.htm#DRDAA131.
Can you not just creat a DUAL table
There are some problem in your code from Oracle point of view which I can think of.
So from comments what I get it that you are not able to use Dual. Dual exists in Oracle. So try running select 1 from dual and if it doesn't work, your query is not running in oracle for sure. Apart from it there are couple of more problem with your query.
Using where before inner join.
Extra closing braces for r
Based of above input, this query might work for you if you are running it in Oracle. Replace dual with sysibm.sysdummy if you are not using Oracle.
Note: You should use proper join syntax(INNER JOIN). I wasn't able to figure out joining condition hence I am using comma to join.
SELECT rma.crspdt AS bic_crspndt,
rma.issr AS bic_issr
FROM rma r,
(SELECT 1 ID FROM dual UNION ALL
SELECT 2 ID FROM dual) dummy
WHERE ( (dummy.id = 1
AND r.bic_crspndt IS NOT NULL)
OR (dummy.id = 2
AND r.bic_issr IS NOT NULL)
)
AND (rma.tp = 'Issued'
OR rma.tp = 'Received')
AND rma.rmasts = 'Enabled'
AND rma.svcnm = 'swift.fin'
I am planning to migrate my application database from Mysql to Mongo with low schema changes. In my new schema I merged two Mysql tables into one Mongo collection. I want to use mongify (https://github.com/anlek/mongify) gem to populate my existing Mysql data into Mongo with newer schema.
How to do this? Is there a way in mongify to merge two Mysql tables into one?
Mysql tables
user
id
name
nickname
type
user_role
id
role
alias
user_id
I merged the above two tables into single collection in Mongo
user
id
name
type
role
alias
Try Left Join: (Tables will be merged)
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
Export that data to sql format and upload it to mongodb
SELECT country INTO customerCountry
FROM customers
WHERE customerNumber = p_customerNumber;
CASE customerCountry -- Here you have to see if that alias data is set
WHEN 'USA' THEN
SET p_shiping = '2-day Shipping'; -- here you have to write Update Query
ELSE
SET p_shiping = '5-day Shipping';
END CASE;
I think it might help you
Fetch the data using JOIN from MySQL and load that data into MongoDB:
Try this:
SELECT U.id, U.name, U.type, UR.role
FROM USER U
INNER JOIN user_role UR ON U.id = UR.user_id;
An alternative if its difficult to merge two tables ad-hoc then run a mongo shell script post-hoc; they are very easy to program (couple o' lines of js) and simple to execute. plus one can apply any needed conversion, such as into json/bson arrays permitted in mongo but not the mysql.
assuming a user and user_role collection (or table) in mongo.
db.user_role.find({}).forEach(function(doc) {
var roles = doc.roles;
// convert mysql format here if needed.
//var roles_array = JSON.parse(roles) // or whatever?
//var alias = doc.alias;
// if alias is null empty or ??
// dont upsert to avoid orphaned user_role records
db.user.update({"_id": doc.user_id}, {"roles": roles, "alias", doc.alias }, {upsert: false, multi: false});
}
Then execute using the mongo shell
mongo localhost:27017/test myjsfile.js
I am using JTable to display the result of a query. Table does not show as XYZ for all columns but it shows XYZ as a header for the fields not existing in database(manipulated fields).
Don't know much of database internals.Please forgive if it's too basic.
rs1 = st1.executeQuery("SELECT product.`id` as `Product ID`,product.`serialnumber` as `Serial Number`, product.`dop` as `Date Of Purchase` FROM product where product.`dop` between '"+from+"' and '"+to+"'");
reportTable.setModel(buildTableModel(rs1));
same query on query browser Output:
Product ID Serial Number Date Of Purchase
1 123244mf43m 08/08/2013
My Output With JDBC is:
id serialnumber dop //table header
1 123244mf43m 08/08/2013
There is a configuration setting described here:
http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-configuration-properties.html
useOldAliasMetadataBehavior
which, if set to true (the default in 5.0.x) will only return aliases (if any) for ResultSetMetaData.getColumnName() or ResultSetMetaData.getTableName() rather than the original column/table name.
Not sure if this is applicable to you, but could be the cause.
dont blame for the database design.I am not its database architect. I am the one who has to use it in current situation
I hope this will be understandable.
I have 3 tables containing following data with no foreign key relationship b/w them:
groups
groupId groupName
1 Admin
2 Editor
3 Subscriber
preveleges
groupId roles
1 1,2
2 2,3
3 1
roles
roleId roleTitle
1 add
2 edit
Query:
SELECT roles
from groups
LEFT JOIN preveleges ON (groups.groupId=preveleges.groupId)
returns specific result i.e roles.
Problem: I wanted to show roleTitle instead of roles in the above query.
I am confused how to relate table roles with this query and returns required result
I know it is feasible with coding but i want in SQL.Any suggestion will be appreciated.
SELECT g.groupName,
GROUP_CONCAT(r.roleTitle
ORDER BY FIND_IN_SET(r.roleId, p.roles))
AS RoleTitles
FROM groups AS g
LEFT JOIN preveleges AS p
ON g.groupId = p.groupId
LEFT JOIN roles AS r
ON FIND_IN_SET(r.roleId, p.roles)
GROUP BY g.groupName ;
Tested at: SQL-FIDDLE
I would change the data structure it self. Since It's not normalised, there are multiple elements in a single column.
But it is possible with SQL, if for some (valid) reason you can't change the DB.
A simple "static" solution:
SELECT REPLACE(REPLACE(roles, '1', 'add'), '2', 'edit') from groups
LEFT JOIN preveleges ON(groups.groupId=preveleges.groupId)
A more complex but still ugly solution:
CREATE FUNCTION ReplaceRoleIDWithName (#StringIds VARCHAR(50))
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE #RoleNames VARCHAR(50)
SET #RoleNames = #StringIds
SELECT #RoleNames = REPLACE(#RoleNames, CAST(RoleId AS VARCHAR(50)), roleTitle)
FROM roles
RETURN #RoleNames
END
And then use the function in the query
SELECT ReplaceRoleIDWithName(roles) from groups
LEFT JOIN preveleges ON(groups.groupId=preveleges.groupId)
It is possible without function, but this is more readable. Made without editor so it's not tested in anyway.
You also tagged the question with PostgreSQL and it's actually quite easy with Postgres to work around this broken design:
SELECT grp.groupname, r.roletitle
FROM groups grp
join (
select groupid, cast(regexp_split_to_table(roles, ',') as integer) as role_id
from privileges
) as privs on privs.groupid = grp.groupid
join roles r on r.roleid = privs.role_id;
SQLFiddle: http://sqlfiddle.com/#!12/5e87b/1
(Note that I changed the incorrectly spelled name preveleges to the correct spelling privileges)
But you should really, really re-design your data model!
Fixing your design also enables you to define foreign key constraints and validate the input. In your current model, the application would probably break (just as my query would), if someone inserted the value 'one,two,three' into the roles table.
Edit
To complete the picture, using Postgres's array handling the above could be slightly simplified using a similar approach as MySQL's find_in_set()
select grp.groupname, r.roletitle
from groups grp
join privileges privs on grp.groupid = privs.groupid
join roles r on r.roleid::text = any (string_to_array(privs.roles, ','))
In both cases if all role titles should be shown as a comma separated list, the string_agg() function could be used (which is equivalent to MySQL's group_concat()
select grp.groupname, string_agg(r.roletitle, ',')
from groups grp
join privileges privs on grp.groupid = privs.groupid
join roles r on r.roleid::text = any (string_to_array(privs.roles, ','))
group by grp.groupname