Please, could anyone tell me how to get information from which attribute of which table is the attribute from the view derived(it could also be a complex expression, not just attribute)through querying system tables or views(INFORMATION_SCHEMA, preferably if possible, because it's standard)
As im diving into my new DBA role and reading as much as I can, I am a little confused on DMV's and system tables. I've been reading through the book "SQL Server 2005 Bible", which has been very helpful. I tend to use it in conjunction with BOL whenever I come across something I want to learn more.
Last Friday, I tinkered around with DMV's, which was really cool, but I ran into something today that confused me.
Basically, it was finding out the recovery model for all the DB's on the server. The code in the book was:
SELECT [name], recovery_model_desc FROM sys.databases;
Which turned exactly what it says it will.
however, I am confused. I initially thought I needed to specify something in the "[name]" section, but realized, that is not the case. My question is, why is that? How do I know when to use [] around something?
Be careful when implementing views (from SQL Server 97/2K). SQL Serverstores the metadata on the view at creation (or the last time it wassaved). This means if you have:SELECT * FROM table1it will put all the fields of table1 in the view's metadata. If youthen change table1 and add (for example) another field, this fieldwill not be visible in the view until you open it in design view andclick save (to update it).
If you create a view such as CREATE VIEW TestView AS Select * FROM customers_table WHERE CustomerID between 213 AND 3443 Each time you want to select from the view - is the View going to perform the WHERE clause on the customers_table, or not? Or does the view already have the virtual rows?, meaning it does not have to perform a where clause (WHERE CustomerID between 213 AND 3443) on the customers_table, and just performs an inner join with the rows it already has?
Hello,I am relatively new to doing non-trivial SQL queries.I have to get data out of 8 diff views based on a parameter Name.There is a view having name-ssn pairs. All other views have SSN field.For a person there MAY NOT be data in all the views.I have to populate data into diff tables in a Report from differentviews.I would like to know what is the best way to approach it.So far I was trying an Inner join from the Name-ssn vies to all otherviews based on the SSN and test for the name field with the inputparameter.I am thinking there will be problem of Cross join if I dont have datain all views about a person.Or the best way is to write query for each view and have all of them ina stored procedure ?Any help will be appreciatedThanksBofo
I wonder how the query will be executed when querying to views.Is database engine will be extract the tables that are used to create the view and query for the result ?
Hi All, I have a requirement where in for a given View name, I need to programatically find out all the tables that are used in the view and I also need to find out how each table in the view is linked.
For example, if I create a simple view like CREATE VIEW XYZ AS
SELECT * FROM TableA INNER JOIN TableB ON TableA.ID = TableB.FKID INNER JOIN TableC ON TableA.ID = TableC.FKID
I need to find out all the Tables involved in the view i.e. TableA, TableB and TableC. I also need to find out how TableA and TableB, TableA and TableC are linked (i mean the join Condition).
Could some one please point me to resources that can help me find the answer to this.
I am getting this exception sporadically in a certain block of code (it usually works): "System.InvalidOperationException: Invalid attempt to MetaData when reader is closed"The code is below:
Hi, I'm having issues trying to get a query working the way I want, it maybe that i'm overly complicating things though.
What I have done so far is have 2 seperate tables one holding details about the item to be booked out with an ID the second linking to the Item via the ID and also having the startdate and the enddate of the booking, thus an item will have multiple rows in the bookings table for multiple bookings.
What I want to have is a "quick" booking method where a user enters the startdate they would like and the enddate, a drop down is then filtered (via a query) returning only the items that are avalible.
The issue i'm having is that because my bookings have multiple rows for each item, for what maybe true in the rules for an item in 1 row maybe false alittle later - i which case the returned data i am getting is incorrect!
Hopefully I have made sense, and maybe someone can help?
my querry for the filter so far: -
SELECT DISTINCT DeviceDetails.Device_ID, DeviceDetails.Device_Name FROM DeviceDetails LEFT OUTER JOIN BookingDetails ON BookingDetails.Device_ID = DeviceDetails.Device_ID WHERE (BookingDetails.Bookout_Date IS NULL) OR (BookingDetails.Bookout_Date >= GETDATE()) AND (@Dateout <= BookingDetails.Bookin_Date) AND (BookingDetails.Bookout_Date >= @Datein) OR (BookingDetails.Bookout_Date >= GETDATE()) AND (@Dateout >= BookingDetails.Bookin_Date) AND (BookingDetails.Bookout_Date <= @Datein)
I was looking in sys.syslogins and sys.sql_logins for a property to tell me if the login is locked but all i see are properties for if the account is enabled or if the account has access. Is there a system view I can query to tell if if the account is locked ? Thanks,
I am stuck on finding a solution to transpose source data from a system via a metadata look-up table into a destination table. I need a method to transpose/pivot the source data into columns (which are by various data-types). The datatypes for each column are listed in a metadata table.
Source Data Table:
Table Name: Source
SrcID AGE City Date 01 32 London 01-01-2013 02 35 Lagos 02-01-2013 03 36 NY 03-01-2013
Metadata Table:
Table Name:Metadata
MetaID Column_Name Column_type 11 AGE col_integer 22 City col_character 33 Date col_date
Destination table:
The source data to be loaded into the destination table(as shown below):
Both of these columns contain npanxx numbers which would be the first 6 digits of a phone number, example 217345 which is in illinois.
Table B Columns:
npanxx, state
table B hold all npanxx numbers in the united states and what state it pertains to.
what i need to do is run a query to check and see what state the OriginatingNumber and the TerminatingNumber are in and decide if both numbers passed are in the same state or not.
so for example in Table A Row 1: OriginatingNumber is 217345 and the TerminatingNumber is 309454. I need to check both of these numbers against table B and it would return that both numbers are in IL. Basically I need to return a result of yes or no. yes they are in the same state or no they are not in the same state.
we run 2008 std edition (I believe r2 on this server, will double check) and I need to find a needle in a haystack.
I am looking at two tables and would like to learn which, if any objects on same db updates these tables. I'd even live with any references to these tables. I already know sql agent is out of the picture. I'm looking for a static approach, not a monitoring one because its possible updates don't occur till month end.
Is there a way in sql server to query the answer to such a question using dmvs or something like dmvs? What if I get bold and want to search all db's on this server for objects that update my two tables even across dbs?
In the mean time, i'll look at scripting all triggers and procs , and doing a search on these table names in the scripts.
I don't know that I've ever seen a way to script all triggers before. Procs I can easily script from the object explorer details. But I'm not sure if in explorer details--> server objects --> triggers does what I hope it does.
can someone tell me where I can look to find a sql command that is being executed by an application against my database? In Oracle, I look in the v$sql_text view - is there something similar in SQL Server 2000 ? Many thanks in advance
I'm trying to access a System Catalog View (sys.database_permissions, and others) from a table valued function. I need to be able to pass the database name into the function so that I can operate on any database. Typically I'd use dynamic SQL to do something like
INSERT INTO #tempTable
EXEC ('SELECT * FROM ' + @DBName + '.sys.database_permissions')
But of course I can't use dynamic SQL inside of a UDF. I know I could do this using a stored procedure, but I'd need the output to be a recordset that I can query.
Has anyone done anything like this? I think I'm stuck.
Hi,I have a few things on my databases which seem to be neither true systemobjects or user objects - notably a table called 'dtproperties' (createdby Enterprise manager as I understand, relating to relationship graphingor something) and some stored procs begining with "dt_" (some kind ofsource control stuff, possible visual studio related). These show up whenI use"exec sp_help 'databaseName'"but not in Ent. Mgr. or in Query Analyzer's object browser, and also notin a third party tool I use called AdeptSQL. I am wondering how thosetools know to differentiate between these types of quasi-system objects,and my real user data. (This is for the purpose of a customized schemagenerator I am writing). I'd prefer to determine this info with systemstored procs (ie sp_help, sp_helptex, sp_...etc) but will dip into thesystem tables if needed.Thanks,Dave
Hi all, lets say i have a table as follows id name1 red2 orange3 green and this has s join to another table via the id table2 id event 1 stop2 stop3 start now if i make a view and drop these two tables the jkoin is there but i would liek to report on all names who have a event of "go"but it gives me no results , which is right . but how can i output all the names and in the evnet put a empty SO name eventred emptyorange emptygreen empty thanksrobby
Hello,I am quite new to ms-sql and I have a problem : I want to create an SQLrequest which would copy serveral records from a table in a given databaseto another table (with exactly the same structure) in another database(theses two tables and databases already exist).Could you please tell me how to do this ? I dont know how to access twodifferent databases in a single SQL request.Thank you for you help.
Hi all, Is there any easy way to not allow a user to see system views? I have set up 1 view for a login, and I have to use an ODBC connection to access it. However, the 3rd party application I'm using is apparently timing out because of the number of tables/views that are returned. TIA! - Mark
I've had a couple problems with SMO and I wonder if anyone else has. Specifically, when I run through stored procedures (just like your example) it is painfully slow. Maybe 5 a second. Another problem is filtering on nonsystem objects with either "SVR.SetDefaultInitFields(typeof(Microsoft.SqlServer.Management.Smo.View), "IsSystemObject"); or View.isSystemObject. Both cases crash my app. Any ideas? Below are two ways that both crash or hang. SVR.SetDefaultInitFields(typeof(Microsoft.SqlServer.Management.Smo.View), "IsSystemObject"); foreach (Microsoft.SqlServer.Management.Smo.View view in viewCollection) {} OR
foreach (Microsoft.SqlServer.Management.Smo.View view in viewCollection) { if (!view.IsSystemObject) {} }
I got a script, which ran on SQL Server 7. After compiling on SQL Server 2012, I came across that the previous script used a system ViewsTables columns named "suid", which no longer operate in SQL Server 2012. After modifying the script with 2012 and replaced suid by SID, it works but the suid column is not appearing in System Views. What if we want to get that column back in SQL Server 2012? is there any possible way?
Hi, while I'm trying to do Select statements, is there a way/setting whereby I don't have to constantly prefix the table names with a prefix? For example, I'm working in multiple environments and they're differentiated by the prefix in their table names, uat.** vs prod.** Any help would be appreciated.
I get a 90-120 second blocking when send 15 or so simultaneous queriesto SQL Server 2000 that query a view made up of two joined tables.After each query is blocking for the same amount of time they allreturn. Further identical queries of this type work in 3-4 seconds(caching?) until hours later where it happens again. If I query thetables directly (without the view) I still get the same blocking. If Iremove the join (it is a simple inner join on two columns) I do not getthe blocking.Any ideas?
This seems like a very simple question but i have never been able tofind an easy answer to it.I have a user table and i do a join with another table, we'll call theother table a results table.The results table has numerous rows with the userid foreign key.I want to make a query that will give me the number of rows in theresults table for each user where the result is some valueThe query is simple to make but will only show the users who have arecord in the results table the meet the where criteria, however i wantto display each user and show a record count of 0 when there are noresults in the results table that match the criteria.for example i have 2 tables.tblUsers_______________userid | username--------------------------1 | user12 | user2tblAnswers________________userid | answer----------------------------1 | 11 | 01 | 42 | 12 | 0if i run the query:select max(username), count(answer) from tblUsersleft outer join tblanswers on tblAnswers.userid = tblUSers.idwhere tblAnswers.answer = 4group by tblUsers.idi just getuser1 | 1i want to getuser1 | 1user2 | 0the only way ive found to do this is with a temp table and a curser tocreate all the users records and go back through an insert the answercount for each user. This approach seems very expensive and requires aquery that is 3 times larger than is needed for the same resultswithout including 0 count records. I know there must be a better way todo this.Any help is appreciated.
I'm using SQL Server 2005 Express Edition, and I have restored a database that was using SQL Server 2000 previous. All of that went fine - sprocs and tables/data all made it.
However, when viewing the tables in the object explorer in the management studio, all the tables are prefixed with the schema name (testuser - so the table names are like: testuser.pn_user). Now, all of the code I have queries the tablename only without prefixing testuser to it - but this doesn't work anymore (invalid object name.)
I've tested, and if I prefix the table names in my code with "testuser.", it starts working again, but would rather avoid doing this. Is there something I can do within Sql Server? I've made the "testuser" account "mapped" to the database I'm using (not sure what that means - I'm more of a software developer than a database guy.) Also, when I do "Properties" for the "testuser," the default database is set to the one I'm trying to query w/o the schema.
All of a sudden none of our merge replications are working. In fact you can't even insert, update or delete and data from the tables in the merge publication. When trying that, we get an error stating:
Msg 550, Level 16, State 1, Procedure MSmerge_ins_E3F43EF8B259476099BBB194A2E1708C, Line 42 The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did not qualify under the CHECK OPTION constraint. The statement has been terminated.
Currently, the only solution I've found is to delete the publication and recreate it. I'm trying to figure out why this happened. It happened on a development server that to my knowledge, hasn't been changed in a week or so outside of changing the server's IP address. Would that cause such an error to occur?
I'm recreating many of my DBA scripts that no longer work in 2005 due to the rework of system tables. It's a risk I lived with knowing that someday the system tables would change. I'm now encountering collation problems, which I do not understand. I know how to fix the problem, but I don't know why the collation issues exist in the first place.
Run the following command.
Select * From sys.all_objects a JOIN master..spt_values b on a.type = b.type
You will receive the following error.
Msg 468, Level 16, State 9, Line 1
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS_KS_WS" in the equal to operation.
Now run sp_help 'sys.all_objects' and look at the collation defintion for columns "type" and "type_desc". In my environment they have a collation of Latin1_General_CI_AS_KS_WS. This is different then the overall default collation of SQL_Latin1_General_CP1_CI_AS, thus causing the error.
My question is why did Microsoft need to make this collation different for these columns?
I am trying to query multiple tables that have the same column. They are a supposed to be a unique ID to the product, but not to the database. I have a primary key already set to each othe tables. The tables do not share anything between them, but i would like to search for these IDs in other tables before my insert command is executed. I am writing my code in VB. example of what i am trying to accomplish. Table1 = TVs ID/SKU_ID/Manufacturer 1 87654 Samsung
I want to search for SKU_ID in multiple tables( I think a total of 9 tables). I want to search between tables to catch for the same SKU_IDs. and if it finds it, raise error. I will be able to figure the vb.net portion. I just dont know how to go about the sql query portion. Thanks in advance and appreciate any help. Thanks!
What I am trying to do now is combine multiple complex queries into one table and query it showing the results on an ASP.net page.
I am currently using SQL Server 2000 backend. Each one of these queries are pretty complex so I created each query as a Stored Procedure. These queries are dynamic by each user, so the results will never be the same globally.
What I have done so far was created a master stored procedure passing the current user's username as a parameter. Within the master SP (Stored Procedure) it creates a temporary table inserts and executes multiple stored procedures and inserts into the temporary directory. Each of the sub stored procedures all have the same columns. After the insert to the temp tables, I then query the temp table and return it to the function it was executed in code and fill it as a System.Data.DataTable. I then bind the DataTable to a Repeater.DataSource.
Problem: When the page is rendered, it returns nothing. I tested the master SP in the data environment and it works fine.
Suspect: ASP.net when the SP is executed, it sees that the data is a disconnected datasource? Perhaps the session in the SQL Server when the temp table is created isn't in SYSOBJECTS system table?
Here is an example of the code from the master SP:
CREATE PROCEDURE dbo.TM_getAlerts @Username varchar(32)ASCREATE TABLE #MyAlerts ([DATE] datetime, [TEXT] varchar(200), [LINK] varchar(200) ) INSERT INTO #MyAlertsEXEC TM_getAlertsNewTasks @Username INSERT INTO #MyAlertsEXEC TM_getAlertsLateTasks @Username SELECT [DATE] AS 'DATE', [TEXT] AS 'TEXT', [LINK] AS LINK FROM #MyAlerts GO
It is a fairly simple call... but why doesn't ASP.net doesn't see it when the the DataTable is filled. I tried just executing one of the sub SP without creating temporary tables and it works flawlessly. But the query in one of the sub SP is a normal but complex select.