Cannot insert default value into SQL database from Win Forms project - sql-server

I have a MS SQL database.
On one of my fields, LotNumber I set the default value to be [dbo].CalculateJulianDate which is a scalar-valued function that takes the current date and creates a Julian date formatted lot number.
When I insert values into my table using SSMS, the value is populated correctly replacing the empty value with the LotNumber.
I am trying to create a visual basic winforms front end for the database in visual studio 2010. I set my datasource, dragged a details view onto a form and I can see the data, make edits to the data, and delete data. However, when I try to insert new data it fills the LotNumber field with NULL.
I do not understand why MS SQL doesn't use the default value rather than the NULL value when data is entered from within my winForms application. I was under the impression that the point of setting up a default value in the SQL schema was to replace NULL values with the default value.
The code for the insert is auto-generated and I can't seem to find it in my application. The only code visible is:
Private Sub Dt_InventoryBindingNavigatorSaveItem_Click(sender As System.Object, e As System.EventArgs) Handles Dt_InventoryBindingNavigatorSaveItem.Click
Me.Validate()
Me.Dt_InventoryBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.CSRPRDDataSet)
End Sub
Does anyone know why SQL Server doesn't insert the default value like it's supposed to? How do I get the default value to populate from within my application?

The default value is used in SQL Server when you don't set that field value at all. If you set it to NULL then it stays set to NULL. If you remove that field from your INSERT statement then the default value will be used.

To make a custom INSERT query on the TableAdapter, right-click on your Table Adapter, choose Add Query and the Query Wizard will appear. Select "Use SQL Statements" and select "INSERT" for the query type.

Related

MS Access DB front end SQL Server Back End Unable to Open any form as New Record after table migration

I have similar issue to one previously posted but none of the answers helped.
I cannot open any form in my DB to a new record.
This all worked before moving tables from Access DB to SQL Server and linking back to them.
All tables have an ID column of datatype integer set as primary key on the server.
All tables have a RowVersion column of datatype datestamp.
All forms are based on a single table as record source.
All columns of datatype = bit have default value set to 0 on the SQL Server.
In Access form, properties are set to allow additions = yes, allow edits = yes, I also set data entry = yes as well which wasn't necessary before SQL server hosted the tables but it didn't help anyway.
I tried on button click event that opens the form:
Private Sub OpenFormNameBtn_Click()
DoCmd.OpenForm "FormName", , , "[CustID]=" & Me![CustID] & " AND [EnvID]= '" & Me![EnvID] & "'"
Forms!DeploymentsF.Form.AllowAdditions = False
Forms!DeploymentsF.Form.AllowAdditions = True
DoCmd.GoToRecord , , acNewRec
End Sub
NOTE: the criteria of custid and envId worked when the tables were in access and I need them to stay this way.
The above caused the auto number ID to appear on the form for an instant but then it disappeared just as quickly! In the code behind the submit button at the bottom of the form (to write the record to the table), it errors out and I see where the Form's ID field = Null in debug so it couldn't write the id in the update statement to the table. I CAN, however, insert a record into the table with a query insert statement on the SQL server no problem AND I can edit records in forms and sub forms and it writes to the tables on the SQL Server.
I also tried a simple form with no criteria and no pre-filling and got the error, "Can't go to the specified record"
I tried button click event: DoCmd.OpenForm "FormName", , , , acFormAdd.
Anyone seen this before and have a solution? I'm out of ideas.

Why does my Dataset display no fields in ReportServer, and can I get it to do so?

I opened a report I started in BIDS in MS SQL Server Report Builder 3.0, as I read an answer here on SO that said that was the easiest way to create a table containing all the values in a Dataset.
So I opened my .rdl file there, selected the Insert tab, then Table > Table Wizard, and the dataset from the "Choose an existing dataset in this report or a shared dataset" list.
When I select the "Next" button of the wizard, though, all lists are empty (Available fields, Column groups, Row groups, Values).
If I select "Next" again, I get, "The values field list must contain at least one field."
Those are auto-populated, though, and, as written above, are as empty as a politican's brain.
Is it because my dataset is a StoredProc, and returns data from a temp table? If so, is there a workaround?
Note: I also tried the Matrix > Matrix Wizard, with the same results.
UPDATE
Also and doubtless relatedly (no pun intended), when I try to run the report from within ReportBuilder, I see:
What a revoltin' development!
UPDATE 2
And when I return to BIDS to work on the project and try to add an Expression in a Matrix, in the Edit Expression dialog, on selecting the Dataset of interest, I get, " dataset has no fields."
Ay, caramba!
UPDATE 3
In response to lrb's answer: I don't know if my SP is really unparseable or not; it does return values from a temp table - Here is the end of it:
SELECT PLATYPUSDESCRIPTION, WEEK1USAGE, WEEK2USAGE, USAGEVARIANCE,
WEEK1PRICE, WEEK2PRICE, PRICEVARIANCE, PRICEVARIANCEPERCENTAGE
FROM #TEMPCOMBINED
ORDER BY PLATYPUSDESCRIPTION;
Could that (using a temp table) be the problem?
UPDATE 4
When adding an Expression to a textbox like so:
=Fields!PLATYPUSDESCRIPTION.Value
...I get the following fingerwag on the Preview tab:
The definition of the report 'bla' is invalid. The Value expression for the textbox 'textbox4' refers to the field 'PLATYPUSDESCRIPTION'. Report item expressions can only refer to fields within the current data set scope or, if inside an aggregate, the specified data set scope.
Surely there's a way to use results from temp tables in an SSRS report, no es cierto?
This will happen when the query or stored procedure can not be parsed with certainty. For example, if your data set is a store procedure that returns something like the following:
IF(#SomVariable=1)
SELECT 1,2,3,4
ELSE
SELECT 'A','B','C'
The above logic in a SP would be horrible, however, the field name and datatypes can not be determined. The same holds true in other edge case scenarios.
What you can do for a work around is to trick the parser by modifying your sp and offering up a clean return statement, then changing the sp back to its original form. Since the metadata is persistent until the next refresh, your values will hold. NOTE : If the problem occurs when returning temporary tables in your dataset see #4 below.
1. Modify your existing stored procedure
ALTER PROCEDURE MyProcedureThatDoesNotParse()
AS
BEGIN
/*COMMENT OUT CURRENT SP LOGIC
...
*/
SELECT
MyField1=1,
MyField2='String',
MyField3=0.01
END
2. IN SSRS Refresh the fields for your dataset.
NOTE : You will see MyField1,MyField2 and MyField3 in the fields list.
3. Revert the changes to your stored procedure.
4. For queries or SP's that return a local #temporary table, global ##temporary table or a table valued #variable, it seems that aliasing the temp structure works. I.E
SELECT * FROM #TABLE --Does not always parse in SSRS
SELECT * FROM #TABLE T --Seems to be able to be parsed by SSRS
Change command type on the report builder, choose " text " and write exec yourprocedurename. It will work

VBA empty string for insert into SQL Server

Here is the situation:
There's a SQL Server database with a Microsoft Access front end. There is a table in the SQL Server database with a column called PackID which is defined as VARCHAR(6) NOT NULL (it has to be NOT NULL because it's part of a composite primary key for this table). Empty strings are legitimate in the PackID column. In fact, they occur quite often. When the user enters data in the UI for this table, and tabs through the PackID field, an error message appears: "Cannot insert the value NULL into column 'PackID'; column does not allow nulls. INSERT fails."
Things that have been tried that do not work:
adding a default constraint on this column in the SQL Server database with a value of '' - apparently the default is only used if the column is omitted from the INSERT statement
setting the Default Value of the PackID field in Access to "" - it behaves as though "" is a NULL
calling the following VBA code when user moves off row in UI (Lost Focus event)
If IsNull(PackID.Value) Then
PackID.Value = ""
End If
Does anyone know how to force an empty string in Access so it's interpreted as an empty string for SQL Server and not a NULL?
Setting the Default Value in the text box Properties for PackID in Access to this
=" "
worked. The space between the double quotes is very important. Leaving the space out causes the insert to fail. In SQL Server LEN(PackID) returns 0. For instance:
SELECT LEN(''), LEN(' ');
both return 0. It appears as though SQL Server treats both of these as empty strings.
An alternative solution to this problem (no Default Value in text box Properties for PackID).
Private Sub Form_BeforeUpdate(Cancel As Integer)
If IsNull(PackID.Value) Or PackID.Value = "" Then
PackID.Value = " "
End If
End Sub
This still uses the concept of passing SQL Server " " (read this as quote space quote) as the field's value. On the UI side, this is an alternative to setting a default value for the field.

SQL Server Default field value

In SQL Server, I have a field which is a bit. I need to default it to 0 on insert of a new record. I thought there was a way for SQL Server to automatically create a constraint without writing code. I thought there was a way to right click on the field and go to properties. I tried but do not see how to default a field.
SQL Server Management Studio: Select the table from the tree, context menu, design table, select the field, in the properties grid at the bottom type a zero (0) in the Default row, save.

MVC 3 date created and modified have default values and triggers in SQL Server 2008 R2, but still want value

I have generated classes (DbContext) modelling my db (SQL Server 2008 R2), and in most of my tables I have the standard ModifiedDate and CreatedDate (No Nulls). Each of these has a default of getdate() in SQLServer, and I have a trigger to update ModifiedDate on any updates.
The generated views included the ModifiedDate and CreatedDate fields, which I don't want (the user shouldn't see these), so I've taken these out, but when adding a new entry using the generated Create view, I get the error "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value".
I then added some default values, and it did add the record, but naturally it added my entered values, and not the SQL getdate() values, which I'd prefer (I want it to show the server time). Checking the object (db.SaveChanges()) the fields have a value of {1/01/0001 12:00:00 AM}.
How can I use these models without entering dates??? I've searched but haven't found my answer... ;-(
This is a common problem in both Entity Framework and Linq to SQL:
In Linq-To-SQL the model doesn't know about the default values, and so attempts to assign them as "null" - which in this case isn't acceptable. To fix this, open the DBML file and set the "Auto Generated Value" option to "true" for the fields in question.
In Entity Framework it's a little different: you set the "StoreGeneratedPattern" on the field to either "Identity" or "Computed". Here's the description:
http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.storegeneratedpattern.aspx
EF will do this automatically for Identity type fields, but not for default value/not null fields. You may want to set your CreatedDate as "Identity" (updated only on insert) and your ModifiedDate as "Computed" (updated on insert and update).
The byproduct of this is that you then will not be able to set the fields via Linq at all - but that's fine in your use case, I think.

Resources