Equivalent query in sql server for INFORMATION_SCHEMA - mysql

I am working on a page where we need to visually compare the schema of same table across the two database-one in sql server and other in mysql.I have to include indexes as well.
now mysql query shows info along with indexes -
select column_name,column_type,table_name,column_key
from INFORMATION_SCHEMA.COLUMNS where table_name = 'tbl_ClientDN'
But for sql server the same query does not return indexes-
select * from INFORMATION_SCHEMA.COLUMNS where table_name = 'tbl_ClientDN'
so i need query to compbine the result of -
sp_helpindex 'tbl_ClientDN'
how to get column_key showing indexes in mssql query.
any suggestion ?

Stay away from INFORMATION_SCHEMA.COLUMNS, especially for indexes, since things like filtered indexes and included columns are not part of the definition. I talk about this in more detail here:
The case against INFORMATION_SCHEMA views
You want to use sys.indexes and sys.index_columns for this. For example:
DECLARE #tablename NVARCHAR(512) = 'dbo.tbl_ClientDN';
SELECT
[Index] = i.name,
[Column] = c.Name,
[Type] = i.type_desc,
PK = i.is_primary_key,
[Unique] = i.is_unique,
[Unique Constraint] = i.is_unique_constraint,
[DESC] = ic.is_descending_key,
[INCLUDE] = ic.is_included_column,
[Filtered] = i.filter_definition -- only for SQL Server 2008+
FROM
sys.indexes AS i
INNER JOIN
sys.index_columns AS ic
ON i.[object_id] = ic.[object_id]
AND i.index_id = ic.index_id
INNER JOIN
sys.columns c
ON ic.column_id = c.column_id
AND ic.[object_id] = c.[object_id]
WHERE
i.[object_id] = OBJECT_ID(#tablename)
ORDER BY [Index], ic.index_column_id;
If you want to do this for all tables at once, then simple changes:
SELECT
[Table] = QUOTENAME(OBJECT_SCHEMA_NAME(i.[object_id]))
+ '.' + QUOTENAME(OBJECT_NAME(i.[object_id])),
[Index] = i.name,
[Column] = c.Name,
[Type] = i.type_desc,
PK = i.is_primary_key,
[Unique] = i.is_unique,
[Unique Constraint] = i.is_unique_constraint,
[DESC] = ic.is_descending_key,
[INCLUDE] = ic.is_included_column,
[Filtered] = i.filter_definition -- only for SQL Server 2008+
FROM
sys.indexes AS i
INNER JOIN
sys.index_columns AS ic
ON i.[object_id] = ic.[object_id]
AND i.index_id = ic.index_id
INNER JOIN
sys.columns c
ON ic.column_id = c.column_id
AND ic.[object_id] = c.[object_id]
ORDER BY [Table], [Index], ic.index_column_id;
More information available in the topics sys.indexes and sys.index_columns.
You also might want to take a look at Kimberley L. Tripp's sp_helpindex2.
EDIT
In general I agree with #BrianWhite's comment. If you are spending any effort on this at all, you should be using a tool for this instead of re-inventing the wheel and trying to write it yourself. Troubleshooting this one query you've probably already spent, in terms of time, the cost of a good tool. Please read this post:
The cost of reinventing the wheel

Perhaps you are after sp_help
http://msdn.microsoft.com/en-us/library/ms187335.aspx
Simply entering
sp_help myTableName
should give you all the data you could want.

Related

Missing text from <memo> field in table in report

I have multiple models in Sparx Enterprise Architect in file-based, i.e. using MS access.
I'm using a custom template to populate a table with data from object's properties, including some with <memo> fields.
This is the query i'm using in the template fragment:
SELECT obj.object_id,
obj.Stereotype,
objp.Property as Prop,
switch(objp.Value = '<memo>', objp.Notes, objp.Value LIKE '{*}',
NULL, 1=1, objp.Value) AS Val,
(SELECT tobj2.ea_guid & tobj2.Name FROM t_object tobj2 WHERE
tobj2.ea_guid = objp.Value) AS [Obj-Hyperlink]
FROM t_object obj
INNER JOIN t_objectproperties objp
ON (obj.object_id = objp.object_id)
WHERE obj.object_id = #OBJECTID# AND obj.Stereotype='Data-
Stream' AND objp.Property NOT IN ('isEncapsulated')
ORDER BY objp.Property ASC;
I found that the when these fields are longer than 249 chars I get an error message when generating the reports and the cell in the generated table is simply empty. This is also noticeable with a query:
The error I'm getting states:
"Error Processing xml document: an invalid character was found in text context"
Is there any workarround to enable including the <memo> fields' data with more than 249 chars in the reports?
Any help is much appreciated.
I've found a workaround for this by joining two queries with a "Union all". The first query will handle the non-memo fields with the switch function and the second one the memo fields without the switch function.
select
obj.object_id,
obj.Stereotype,
objp.Property as Prop,
objp.Notes AS Val,
(
SELECT
tobj2.ea_guid & tobj2.Name
FROM
t_object tobj2
WHERE
tobj2.ea_guid = objp.Value
) AS [Obj-Hyperlink]
from
t_objectproperties objp
left join t_object obj on (obj.object_id = objp.object_ID)
where
obj.object_id = #OBJECTID#
AND obj.Stereotype = 'Data-Stream'
AND objp.Property NOT IN ('isEncapsulated')
AND objp.Value = "<memo>"
UNION ALL
SELECT
obj2.object_id,
obj2.Stereotype,
objp2.Property as Prop,
switch(
objp2.Value LIKE '{*}', NULL, 1 = 1, objp2.Value
) AS Val,
(
SELECT
tobj2.ea_guid & tobj2.Name
FROM
t_object tobj2
WHERE
tobj2.ea_guid = objp2.Value
) AS [Obj-Hyperlink]
FROM
t_object obj2
INNER JOIN t_objectproperties objp2 ON (obj2.object_id = objp2.object_id)
WHERE
obj2.object_id = #OBJECTID#
AND obj2.Stereotype = 'Data-Stream'
AND objp2.Property NOT IN ('isEncapsulated')
and objp2.Value <> "<memo>"
order by
3 asc;
Thanks a lot #geertbellekens for your comment which was crucial to find this solution.

Select * from view more than 10x slower than executing the views create statement directly with MySQL 5.7

I have created a view as a join of several tables to hide the complexity.
Now when I execute a select * from view it takes more than 10x of the execution time it takes to execute the select statement directly, that defines the view (about 70 ms vs 900 ms).
This behaviour occurs on a MySQL 5.7.23 server.
I compared the execution plans for both queries and the only difference (as expected) is the derived table:
Is this a normal behaviour of views or how can I fix it?
P.S.:
The create view statement as requested (names where obfuscated):
create view vrs as select
rs."id" as "id",
l."language" as "language",
rss."t" as "discriminator",
rss."type" as "type",
coalesce(lt3."text", concat('!',s3."textkey",'(',l."language",')')) as "typeText",
rss."model" as "model",
coalesce(lt2."text", concat('!',s2."textkey",'(',l."language",')')) as "modelText",
rs."name" as "name",
rs."reqCATGroup" as "CATGroup",
rs."devID" as "devID",
case s."builtIn"
when 0 then s."displayName"
else (select lt1."text"
from loctext lt1
where lt1."language"=l."language"
and lt1."textkey"=s."displayName")
end as "sName",
s."id" as "sId",
s."postcode" as "sPostcode",
s."place" as "sPlace",
s."street" as "sStreet",
s."streetNumber" as "sStreetNumber",
s."tId" as "tId",
t."tName" as "tName",
rss."CCVMajor" as "CCVMajor",
rss."CCVMinor" as "CCVMinor",
rss."CCVPatch" as "CCVPatch",
rss."CCHV" as "CCHV",
coalesce(lHw."text", concat('!',sHw."textkey",'(',l."language",')')) as "CCHVText",
rss."MCVMajor" as "MCVMajor",
rss."MCVMinor" as "MCVMinor",
rss."MCVPatch" as "MCVPatch",
rss."level",
coalesce(lLevel."text", concat('!', sLevel."textkey", '(', l."language", ')')) as "levelText",
rss."event",
coalesce(lEvent."text", concat('!', sEvent."textkey", '(', l."language", ')')) as "eventText",
rss."isBusy" as "isBusy",
rss."tsLastComIn" as "tsLastCom",
rss."tsBT" AS "tsBT",
b1."ordinal" as "isSending",
coalesce(ltSend."text", concat('!',b1."textkey",'(',l."language",')')) as "isSendingText",
b2."ordinal" as "isReceiving",
coalesce(ltReceive."text", concat('!',b2."textkey",'(',l."language",')')) as "isReceivingText",
rs."historyCreateDevTs",
rs."historyCreateDevUserId",
rs."historyCreateDevUserLoginName",
rs."historyModifyDevLinkTs",
rs."historyModifyDevLinkUserId",
rs."historyModifyDevLinkUserLoginName",
rs."monitorStartTs",
rs."monitorEndTs"
from synch rss
cross join loclanguages l
join cfgrs rs on rs."id" = rss."id"
join cfgs s on s."id" = rs."sId"
join cfgt t on t."id" = s."tId"
left join locmodel s2 on s2."ordinal" = rss."model"
left join loctext lt2 on lt2."textkey" = s2."textkey" and lt2."language" = l."language"
left join loctype s3 on s3."ordinal" = rss."type"
left join loctext lt3 on lt3."textkey" = s3."textkey" and lt3."language" = l."language"
left join locbooleanrange b1 on rs."sending"+1 = b1."ordinal"
left join loctext ltSend on ltSend."textkey" = b1."textkey" and ltSend."language" = l."language"
left join locbooleanrange b2 on rs."receiving"+1 = b2."ordinal"
left join loctext ltReceive on ltReceive."textkey" = b2."textkey" and ltReceive."language" = l."language"
left join loceventlevel sLevel on sLevel."ordinal" = rss."level"
left join loctext lLevel on lLevel."textkey" = sLevel."textkey" and lLevel."language" = l."language"
left join locevent sEvent on sEvent."ordinal" = rss."event" and sEvent."type" = rss."type"
left join loctext lEvent on lEvent."textkey" = sEvent."textkey" and lEvent."language" = l."language"
left join loccchv sHw on sHw."ordinal" = rss."CCHV"
left join loctext lHw on lHw."textkey" = sHw."textkey" and lHw."language" = l."language"
where rs."deleted" = 0
;
P.P.S.: The complete execution plans look like this:
direct call:
view:
This link is for MySQL 8.0, but when I last had performance issues with Views in MySQL 5.6, 5.7, and went digging, I got the same answer: You basically cannot take advantage of Indexes when using Views.
https://dev.mysql.com/doc/refman/8.0/en/view-restrictions.html
I personally found Views in MySQL to Not be useful overall, due to limitations like the ones described above, particularly due to the performance hit.
Readers - if somehow Views in MySQL can perform, I certainly missed a key memo somewhere. Please correct me if this is the case.

how to perform count using nested select in a select statement

So here is the issue. I'm trying to write a new fillrate report because the one built in is not good enough... I'm trying to run a single select statement to return both, a count of how many times an item was ordered for a specific month, and then also a count of how many times it was invoiced/shipped in full.
This code is obviously wrong, I also currently have it restricted to only look at AUG of 2015, but that is just to simplify results during testing.
I can't figure out how to do the 2nd count... This is what I was trying (brain stuck on old for each loop logic):
select inv_mast.item_id,
inv_mast.item_desc,
"YEAR" = year(oe_line.required_date),
"MONTH" = month(oe_line.required_date),
"ORDERS" = count(1),
"HITS" = (
select count(1)
from invoice_line
where invoice_line.order_no = oe_line.order_no
and invoice_line.oe_line_number = oe_line.line_no
and invoice_line.qty_shipped = oe_line.qty_ordered
)
from oe_line,
inv_mast,
inv_loc
where inv_mast.inv_mast_uid = oe_line.inv_mast_uid
and inv_mast.delete_flag = 'N'
and inv_mast.inv_mast_uid = inv_loc.inv_mast_uid
and inv_loc.location_id = '101'
and year(oe_line.required_date) = '2015'
and month(oe_line.required_date) = '8'
group by inv_mast.item_id,
inv_mast.item_desc,
year(oe_line.required_date),
month(oe_line.required_date)
order by inv_mast.item_id
To me it would seem like you could rewrite the query to use a left join on the invoice_line table instead. Without any proper test data I can't guarantee it is correct, but I think it should be.
Besides the left join I also changed to explicit joins and moved the aliases as I don't think MySQL supports the alias = column syntax.
select inv_mast.item_id,
inv_mast.item_desc,
year(o.required_date) as "YEAR",
month(o.required_date) as "MONTH",
count(1) as "ORDERS",
count(invoice_line.order_no) as "HITS"
from oe_line o
join inv_mast on inv_mast.inv_mast_uid = o.inv_mast_uid
join inv_loc on inv_mast.inv_mast_uid = inv_loc.inv_mast_uid
left join invoice_line on invoice_line.order_no = o.order_no
and invoice_line.oe_line_number = o.line_no
and invoice_line.qty_shipped = o.qty_ordered
where inv_mast.delete_flag = 'N'
and inv_loc.location_id = '101'
and year(o.required_date) = '2015'
and month(o.required_date) = '8'
group by inv_mast.item_id,
inv_mast.item_desc,
year(o.required_date),
month(o.required_date)
order by inv_mast.item_id;

unknown class: Fixnum Rails MySQL query - inserting variable breaks my search

I had a query which was working just fine:
#schedule = Schedule.find(params[:id])
#schedule_tasks = ScheduleTask.select("s.*, t.*, t.*, d.*, st.*").from("schedule_tasks st").
joins("left join schedules s ON s.id = st.schedule_id").
joins("left join tasks t ON t.id = st.task_id").
joins("right join days d ON d.id = st.day_id").
order("d.number, t.name").
group_by{|d| d.number}
I had to refine my search to only schedule_tasks with a specific schedule_id, so I edited the second line to:
joins("left join schedules s ON s.id = st.schedule_id AND s.id = ?", #schedule.id).
This has cause the following error:
unknown class: Fixnum
The error goes away if I take out the group_by - but I need that, and I have tried hard coding in the number instead of #schedule.id and that does not work either, a google search does not reveal a lot of details on this error.
For anyone coming here from Google, I used plain string interpolation to fix this issue. This method is vulnerable to SQL Injection, so make sure you type check your variables before using them.
In this case I would do
#schedule_id = #schedule.id
.
.
.
joins("left join schedules s ON s.id = st.schedule_id AND s.id = #{#schedule_id}")
Rather than following learning_to_swim's answer, which as noted is at risk of SQL injection, couldn't you cast your #schedule_id to a string?
#tasks = ScheduleTask.joins("left join [...] s.id = ?", #schedule.id.to_s)

SQL - Make this statement faster i.e. less duration, reads

Given the following tables:
Orders (OrderID, OrderStatus, OrderNumber)
OrderItems(OrderItemID, OrderID, ItemID, OrderItemStatus)
Orders: 2537 records
Order Items: 1319 records
I have created indexes on
Orders(OrderStatus)
OrderItems(OrderID)
OrderItems(OrderItemStatus)
I have the following SQL statement (generated by LinqToSql) which when executed, has:
- duration = 8789
- reads = 7809.
exec sp_executesql N'SELECT COUNT(*) AS [value]
FROM [dbo].[Orders] AS [t0]
WHERE ([t0].[OrderStatus] = #p0) OR (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[OrderItems] AS [t1]
WHERE ([t1].[OrderID] = [t0].[OrderID]) AND ([t1].[OrderItemStatus] = #p1)
))',N'#p0 nvarchar(2),#p1 nvarchar(2)',#p0=N'KE',#p1=N'KE'
Is there anything else which I can do to make it faster?
make all those nvarchars parameters varchars if the columns in the table are varchars
))',N'#p0 varchar(2),#p1 varchar(2)',#p0=N'KE',#p1=N'KE'
See also here: sp_executesql causing my query to be very slow
Count on a single index rather than *
This might generate some better sql.
IQueryable<int> query1 =
from oi in db.OrderItems
where oi.OrderItemStatus == theItemStatus
select oi.OrderID;
IQueryable<int> query2 =
from o in db.Orders
where o.OrderStatus == theOrderStatus
select o.OrderID;
IQueryable<int> query3 = query1.Concat(query2).Distinct();
int result = query3.Count();