Linqpad can table with column same name as table name - linqpad

Hello all i have a small issue with Linqpad with a poorly setup Database
Firstly i have a database where the creator has tables with column named the same as table which he is using as an enabled field.
In Addition to this these tables have the columns Content and Value.
After experimenting with this if the table has a column named the same as the Table it renames the column to Content and then Value if it has a column name similarly named.
if i then try to query (below) i loose the column with the same column name as the table. Does anyone know of any method to get around this. as it makes linqpad use impossible as this is prominent over all the database tables i am currently using?
Example below
If i have
CREATE TABLE [dbo].[TestTable](
[TestTableID] [int] NOT NULL,
[TestTable] [varchar](max) NULL,
[Content] [varchar](max) NULL,
[Value] [varchar](max) NULL
)
As you can see im missing the

What happens is that if your table "foo" contains a field named "foo", then this field gets renamed to "content" in linqpad.
In your case, the field "content" already exists, so you end up with only one of the two created in the context's table (thus the "missing" field).
As a workaround, you can try to avoid the collision by changing the names (table name, field name, content field name), or creating a view with aliased names to avoid collisions.

This got me going for the better part of an hour now, but I think I found a working solution for you.
the problem is the Linq-To-Sql provider in Linqpad itself. If you open up Visual Studio and create a context class based on your database, you will notice the column TestTable gets renamed to TestTable1.
So what I have done to take advantage of this, is created a new project of type "class library" - target Framework 4.0.
In this I added a new Linq-to-Sql class and dragged the TestTable into it.
Go into your class1.cs and insert: (I don't know if this is neccessary)
//I named my context L2S. Replace accordingly
public L2SDataContext context = new L2SDataContext();
Compile
Add a new connection to Linqpad using a typed context!
Connect to your server
Query!

Related

Is USER_NAME column unique in HANA DB USERS table?

Is USER_NAME field/column unique in HANA Database USERS table? I am seeing just number in USER_ID values.
Like BNAME in SAP USR02 table, I want to know what is the unique(or equivalent to bname) value field in HANA DB USERS table.
Amandeep Modgil's answer is not wrong but does not fully answer the question.
Of course, the documentation makes it clear that user names in SAP HANA need to be unique. However, it does not specifically explain whether or how this is enforced/guaranteed.
The "DB dev way" to find out something like this is to check the table structure used by HANA to store users.
Looking at the PUBLIC.USERS objects, we realize: this is not a table but a view instead.
Views don't have any constraints assigned to them, so any primary key or unique constraint must be implemented with one of the tables referenced by the view.
The next step is to review the source code for the view. In SAP HANA Studio one can simply mark the name of the view in the SQL editor and choose "Show Definition" from the context menu.
For PUBLIC.USERS this opens two(!) new windows:
one for the public synonym (there really is no PUBLIC schema, just synonyms) for USERS
and another one for the view SYS.USERS
This SYS schema is where SAP HANA system objects are implemented, so it's not surprising to find the view for USERS here.
In my HANA Express 2.00.045 system, the source code for the view surprisingly begins with
CREATE **ROW TABLE** "SYS"."USERS" ( "USER_NAME",
"USER_ID",
"USERGROUP_NAME" ...
That's weird at the very least, and I suspect it might be a bug as all other metadata entries for this object make it clear that this is in fact a view.
But I digress...
The question to answer was: where is the uniqueness of USER_NAME enforced?
Scrolling down the last main FROM-clause of the SYS.USERS-view points to a table: SYS.P_USERS_.
The trailing underscore in the name indicates that this is an internal HANA object that should never be directly used by any user or application. But that does not stop us from looking at it. Appropriate privileges are required for that, though. The "normal" application user account probably won't be able to directly look at this table's definition. I'm just using the SYSTEM user in this case.
Anyhow, we use the same technique as before: mark the SYS.P_USERS_ table in the SQL Editor, choose "Show definition" and we get: the definition of the table that holds the user accounts in SAP HANA.
The first three columns are defined like this:
Name SQL Data Type Dimension Column Store Data Type Key Not Null
OID BIGINT FIXED X
NAME NVARCHAR 256 STRING
LAST_SUCCESSFUL_CONNECT TIMESTAMP LONGDATE ...
Notice how there is no primary key defined on this table and how only OID has a NOT NULL constraint?
Clearly, the uniqueness of NAME is not guaranteed by table constraints.
So what else could it be?
Let's switch to the Indexes tab of the table definition and we find:
IDX_P_USERS_OID, indexed columns: "OID" ASC
IDX_P_USERS_NAME, index columns: "NAME" ASC
AND for both of these indexes the Unique-flag is set.
And there we have it:
Both OID (exposed as USER_ID) and NAME (exposed as USER_NAME) are unique in SAP HANA, enforced by unique indexes on the internal table that holds these user account entries.
You can look up the schema information on SAP portal link below:
https://help.sap.com/viewer/4fe29514fd584807ac9f2a04f6754767/2.0.01/en-US/21026099751910148e0cdbddc75652b8.html
Although it does not tell you whether a particular column is the primary key or need to be unique, but you can combine this information with the data from following system view and get the information you are after.
https://help.sap.com/viewer/4fe29514fd584807ac9f2a04f6754767/2.0.05/en-US/210197377519101481cfb213f0b84848.html
I have highlighted the columns in the tables system view you need in the screenshot below

Cakephp 3 with SQL Server 2012

I am writing RESTful API using cakephp 3.6 for SQL Server 2012. Some API's created and working fine.
But unfortunately not for one table. This table have primary key but its value is not auto incremented. When I am assigning its value API its generating error
SQLSTATE[23000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Cannot insert the value NULL into column 'Id', table 'AccountsLive.dbo.Books'; column does not allow nulls. INSERT fails
I can't keep its primary key auto incremented.
When I create view to add it from browser. It does not create field for Id field. Then I try to create input field for Id field, its not going to display it on books input form.
Please help me to solve this issue, I will be thankful to you.
The assumption is that your id columns will be auto-incrementing. If there's a good reason(*) why you can't do that here, you'll need to add the input field (as you found), and also add it to the _accessible list in the Book entity.
(*) The number of situations where having your id column not auto-incrementing (and not a UUID) makes sense is really very small. Be very sure that this really does apply to you, as it moves all responsibility for avoiding overwriting records due to duplication onto you instead of the database.

MS Access not working after swapping ODBC linked table with ODBC linked view

My company uses an SQL Server database, with Access as a front end. One of the biggest tables on the server is called tbl_Contacts. The primary key, "ContactID" was setup as an auto-incrementing "int" data type. Turns out yesterday afternoon, the limits of the "int" type ran out, and no new contacts could be added to the table.
At first I tried just updating the data type to "bigint", but then Access couldn't recognize the data type and showed "Deleted" for all the fields in the Contacts table.
I read a bunch of different articles and realized that Access 2010 cannot understand the bigint data type, and that I would need to cast the field to a different type that Access could understand.
I ended up making a View of tbl_Contacts and used this SQL to modify the ContactID field, including all the other fields in the table as is.
CAST(ContactID AS Decimal(15, 0)) AS ContactID
I then renamed the old linked table in Access to tbl_Contacts_OLD, added the new ContactsView table into Access with an ODBC connection, and renamed the View to "tbl_Contacts".
I thought everything was working, because I could add new records to the table again, but it turns out some things are still not working.
The only thing I can imagine is that other tables in my database are expecting "ContactID" to be a "Long Integer", and they aren't liking it being a "Decimal".
When I try to use a form that adds data to a table "tbl_CallLog", which links to "tbl_Contacts", I get this error.
Run-time error '3101'
The MS Access database engine cannot find a record in the table 'tbl_Contacts' with key matching field(s) 'ContactID'
Is there another data type I should be casting to that Access 2010 can recognize and use? Is there maybe a step I still need to do, perhaps casting the decimal value to yet another data type within Access?
Do I need to convert the data type on all other tables that reference the original Contacts table so they're linked fields are now decimal data types?
BigInt can be understood only by Access 2016.
The data types for a record id should be either Long or GUID. Long is by far the most commonly used.
So this isn't the best solution in the world, but I finally got my problem fixed doing the following.
My tbl_Contacts table only has 99k records in it, but due to various reasons, and the table being 20 years old, the IDENTITY SEED was at 2+ billion, the limits of the "int" datatype. I looked through the IDs and found a gap of 120k numbers, so I used this query to reset my seed value.
DBCC CHECKIDENT ('[tbl_Contacts]', RESEED, -92801);
GO
I've created several test contacts now, and the first one had the ID number -92800.
This should hold me until I can get a new CRM system in place in the middle part of the year.
Thanks for the comments, Gustav.

SQL, How to change column in SQL table without breaking other dependencies?

I'm sure this might be quite common query but couldn't find good answer as for now.
Here is my question:
I've got a table named Contacts with varchar column Title. Now in the middle of development I want to replace field Title with TitleID which is foreign key to ContactTitles table. At the moment table Contacts has over 60 dependencies (other tables, views functions).
How can I do that the safest and easiest way?
We use: MSSQL 2005, data has already been migrated, just want to change schema.
Edit:
Thanks to All for quick replay.
Like it was mentioned Contacts table has over 60 dependents, but when following query was run, only 5 of them use Title column. Migration script was run, so no data changes required.
/*gets all objects which use specified column */
SELECT Name
FROM syscomments sc
JOIN sysobjects so ON sc.id = so.id
WHERE TEXT LIKE '%Title%' AND TEXT LIKE '%TitleID%'
Then I went through those 5 views and updated them manually.
Use refactoring methods. Start off by creating a new field called TitleID, then copy all the titles into the ContactTitles table. Then, one by one, update each of the dependencies to use the TitleID field. Just make sure you've still got a working system after each step.
If the data is going to be changing, you'll have to be careful and make sure that any changes to the Title column also change the ContactTitles table. You'll only have to keep them in sync while you're doing the refactoring.
Edit: There's even a book about it! Refactoring Databases.
As others pointed out it depends on your RDBMS.
There are two approaches:
make a change to the table and fix all dependencies
make a view that you can use instead of direct access to the table (this can guard you against future changes in the underlying core table(s), but you might loose some update functionality, depending on your DBMS)
For Microsoft SQL Server Redgate have a (not free) product that can help with this refactoring http://www.red-gate.com/products/sql_refactor/index.htm
In the past I have managed to do this quite easily (if primitively) by simply getting a list of things to review
SELECT * FROM sys.objects
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Contacts%'
(and possibly taking dependencies information into account and filtering by object type)
Scripting all the ones of interest in Management Studio then simply going down the list and reviewing them all and changing the CREATE to ALTER. It should be quite a simple and repetitive change even for 60 possible dependencies. Additionally if you are referring to a non existent column you should get an error message when you run the script to ALTER.
If you use * in your queries or adhoc SQL in your applications obviously things may be a bit more difficult.
Use SP_Depend 'Table Name' to check the Dependencies of the table
and then Use the SP_Rename to Rename the Column Name which is very useful.
sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is renamed. If a renamed index is tied to a PRIMARY KEY constraint, the PRIMARY KEY constraint is also automatically renamed by sp_rename.
and then start Updating the Procedure and Functions one by one there is no other good option for change like this if you found then tell me too.

Inheritance in database?

Is there any way to use inheritance in database (Specifically in SQL Server 2005)?
Suppose I have few field like CreatedOn, CreatedBy which I want to add on all of my entities. I looking for an alternative way instead of adding these fields to every table.
There is no such thing as inheritance between tables in SQL Server 2005, and as noted by the others, you can get as far as getting help adding the necessary columns to the tables when you create them, but it won't be inheritance as you know it.
Think of it more like a template for your source code files.
As GateKiller mentions, you can create a table containing the shared data and reference it with a foreign key, but you'll either have to have audit hooks, triggers, or do the update manually.
Bottom line: Manual work.
PostgreSQL has this feature. Just add this to the end of your table definition:
INHERITS FROM (tablename[, othertable...])
The child table will have all the columns of its parent, and changes to the parent table will change the child. Also, everything in the child table will come up in queries to the parent table (by default). Unfortunately indices don't cross the parent/child border, which also means you can't make sure that certain columns are unique across both the parent and child.
As far as I know, it's not a feature used very often.
You could create a template in the template pane in Management Studio. And then use that template every time you want to create a new table.
Failing that, you could store the CreatedOn and CreatedBy fields in an Audit trail table referencing the original table and id.
Failing that, do it manually.
You could use a data modeling tool such as ER/Studio or ERWin. Both tools have domain columns where you can define a column template that you can apply to any table. When the domain changes so do the associated columns. ER/Studio also has trigger templates that you can build and apply to any table. This is how we update our LastUpdatedBy and LastUpdatedDate columns without having to build and maintain hundreds of trigger scripts.
If you do create an audit table you would have one row for every row in every table that uses the audit table. That could get messy. In my opinion, you're better off putting the audit columns in every table. You also may want to put a timestamp column in all of your tables. You never know when concurrency becomes a problem. Our DB audit columns that we put in every table are: CreatedDt, LastUpdatedBy, LastUpdatedDt and Timestamp.
Hope this helps.
We have a SProc that adds audit columns to a given table, and (optionally) creates a history table and associated triggers to track changes to a value. Unfortunately, company policy means I can't share, but it really isn't difficult to achieve.
If you are using GUIDs you could create a CreateHistory table with columns GUID, CreatedOn, CreatedBy. For populating the table you would still have to create a trigger for every table or handle it in the application logic.
You do NOT want to use inheritance to do this! When table B, C and D inherits from table A, that means that querying table A will give you records from B, C and D. Now consider...
DELETE FROM a;
Instead of inheritance, use LIKE instead...
CREATE TABLE blah (
blah_id serial PRIMARY KEY
, something text NOT NULL
, LIKE template_table INCLUDING DEFALUTS
);
Ramesh - I would implement this using supertype and subtype relationships in my E-R model. There are a few different physical options you have of implementing the relationships as well.
in O-R mapping, inheritance maps to a parent table where the parent and child tables use the same identifier
for example
create table Object (
Id int NOT NULL --primary key, auto-increment
Name varchar(32)
)
create table SubObject (
Id int NOT NULL --primary key and also foreign key to Object
Description varchar(32)
)
SubObject has a foreign-key relationship to Object. when you create a SubObject row, you must first create an Object row and use the Id in both rows