Monday, March 26, 2012
Problems with SP and NULL values.
I have two servers, one with SQL 7.0 SP4 (Production server) and the
development server with SQL 2000 SP3.
One developer tells me that in the development server the store procedures
he creates permits the NULL output. On the production server, he says that
the SP migrated, does not permit a NULL output.
Is this true? how can i check this?
Thanks all.Output *parameters* may be NULL. *RETURN values* must be a non-NULL integer,
although this is handled as a warning rather than an error in 2000. May have
been different in 7.0, I don't recall. Don't try to return a NULL RETURN
value.
You use SQL2000 as a dev box for a 7.0 production server?! Good luck! ;-)
David Portas
SQL Server MVP
--|||Thanks David, the developer has corrected the scripts and now all is working
fine.
I dont unterstand why the developers have migrated to SQL 2000 without
permission, i am new to the company, so my next task will be migrate the SQl
7.
Thanks again.
Wednesday, March 21, 2012
Problems with Nulls and SQL UDT's
I created a UDT in C# that is working fine except when I request rows where the type is null.
If I use SELECT Film.ToString() FROM ImageData it works fine, or any property they return Null as expected
but if I use SELECT Film FROM ImageData it produces the error below
An error occurred while executing batch. Error message is: Data is Null. This method or property cannot be called on Null values.
I looked through all the examples in C# and my code matches the pattern for nulls exactly. Can anyone shead some light on what attribute I may have to add or method I should override which is not documented.
This was a bug. Please see http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=125552
Cheers,
Problems with null values
I have a table with the following fields:
patchbayLineout,summary,lineBoxName,effectid,compr essorID,preAmpID,synthID,mixingConsoleID,drumMachi neID.
On the same row as PatchBayLineOut, the part connected there should have its name showing. In the table, the ID is present. For instance, a LineOut that has a Linebox connected contains LineBoxID, and NULL in all the other places.
The output I want is this:
1, Summary text, LB.Name, null, null, null, null, null, null
2, Summary text, null, E.Name, null, null, null, null, null
3, Summary text, null, null, C.Name, null, null, null, null
4, Summary text, null, null, null, PA.Name, null, null, null
Can anyone help me?I think you want to perform a lot of outer joins like this:
select t.id, t.summary, lb.name, e.name, c.name, pa.name, ...
from t
left outer join lb on lb.id = t.lb_id
left outer join e on e.id = t.e_id
... etc.sql
Problems with null values
Unfortunately, when I go from rst to XML, any null values are chopped off and don't appear in the XML tree. This causes problems in further developments.
It would appear that the easiest way to fix the problem is to guarrantee that there are no nulls in the output data.
I've tried ' ' + tbl.column as NewCol but when tbl.column is null, the result is null also.
suggestions?
For the record, for some damn reason the FOR XML RAW command does not work on my SQL. Don't know why, but I'm trying to find a work around.select coalesce(tbl.column,'') as newcol
replaces null with zero-length string
use 0 for numeric fields, i guess
rudy|||u can check the null value while retreiving the value from a recordset to a variable by iif(isnull(rsAdo("column")),"",rsAdo("column"))|||A variation of r937's answer:
SELECT IsNull(Field, 0) AS Field1
or
SELECT IsNull(Field, 'unknown') AS Field1
Problems with null text boxes when doing like search
I have three text boxes firstname, lastname, dob. It is set up to do a like search on the the text boxes. If a user wants to do a search for just the last name it will not work. You must type in something in all three boexes. Doesn't anybody know how to correct this. Here is the code. Thanks.
<%
@.PageLanguage="VB" %><!
DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><
scriptrunat="server">ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.LoadGridView1.Visible =
FalseGridView2.Visible =
FalseEndSubProtectedSub Button1_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles Button1.ClickGridView1.DataSourceID =
"SqlDataSource1"GridView1.DataBind()
GridView2.DataSourceID =
NothingGridView2.DataBind()
GridView1.Visible =
TrueEndSubProtectedSub Button2_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles Button2.ClickGridView2.DataSourceID =
"SqlDataSource2"GridView2.DataBind()
GridView1.DataSourceID =
NothingGridView1.DataBind()
GridView2.Visible =
TrueEndSubProtectedSub SqlDataSource1_Selecting(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)EndSub
</
script><
htmlxmlns="http://www.w3.org/1999/xhtml"><
headid="Head1"runat="server"><title>Meditech Radiology Numbers</title><linkhref="StyleSheet.css"rel="stylesheet"type="text/css"/></
head><
body><formid="form1"runat="server"><divid="master_headertop"><asp:HyperLinkID="HomePageLink"runat="server"ImageUrl="~/images/headertop_img.jpg"/></div><divid="master_menu"><divclass="sidebar"><divclass="sidebarheader">
Demographic search
</div><divid="master_sidebarSamples"class="sidebarcontent"> <table><tr><tdstyle="width: 100px"><asp:LabelID="Label1"runat="server"Text="First"></asp:Label></td><tdstyle="width: 100px"><asp:TextBoxID="FirstName"runat="server"></asp:TextBox></td></tr><tr><tdstyle="width: 100px; height: 26px;"><asp:LabelID="Label2"runat="server"Text="Last"></asp:Label></td><tdstyle="width: 100px; height: 26px;"><asp:TextBoxID="LastName"runat="server"></asp:TextBox></td></tr><tr><tdstyle="width: 100px"><asp:LabelID="Label3"runat="server"Text="DOB"></asp:Label></td><tdstyle="width: 100px"><asp:TextBoxID="DOB"runat="server"></asp:TextBox></td></tr><tr><tdstyle="width: 100px"></td><tdstyle="width: 100px"><asp:ButtonID="Button1"runat="server"Text="Search"/></td></tr></table></div></div><divclass="sidebar"><divclass="sidebarheader">Search by Mr#
</div><divid="master_sidebarWalkthroughs"class="sidebarcontent"> <table><tr><tdstyle="width: 100px"><asp:LabelID="Label5"runat="server"Text="MR #"></asp:Label></td><tdstyle="width: 100px"><asp:TextBoxID="MR"runat="server"></asp:TextBox></td></tr><tr><tdstyle="width: 100px"></td><tdstyle="width: 100px"><asp:ButtonID="Button2"runat="server"Text="Search"/></td></tr></table></div></div> <br/> </div><divid="master_content"style="height: 399px"><asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False"DataSourceID="SqlDataSource1"><Columns><asp:BoundFieldDataField="LAST"HeaderText="LAST"SortExpression="LAST"/><asp:BoundFieldDataField="FIRST"HeaderText="FIRST"SortExpression="FIRST"/><asp:BoundFieldDataField="DOB"HeaderText="DOB"SortExpression="DOB"/><asp:BoundFieldDataField="RAD #"HeaderText="RAD #"SortExpression="RAD #"/><asp:BoundFieldDataField="MR#"HeaderText="MR#"SortExpression="MR#"/><asp:BoundFieldDataField="EXAM#"HeaderText="EXAM#"SortExpression="EXAM#"/><asp:BoundFieldDataField="EXAM DATE"HeaderText="EXAM DATE"SortExpression="EXAM DATE"/><asp:BoundFieldDataField="EXAM NAME"HeaderText="EXAM NAME"SortExpression="EXAM NAME"/><asp:BoundFieldDataField="ORDER DOC"HeaderText="ORDER DOC"SortExpression="ORDER DOC"/><asp:BoundFieldDataField="Column 9"HeaderText="Column 9"SortExpression="Column 9"/></Columns></asp:GridView><asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:RADConnectionString2 %>"SelectCommand="SELECT * FROM [Full File through 2006] WHERE (([FIRST] LIKE '%' + @.FIRST + '%') AND ([LAST] LIKE '%' + @.LAST + '%') AND ([DOB] LIKE '%' + @.DOB + '%'))"OnSelecting="SqlDataSource1_Selecting"><SelectParameters><asp:ControlParameterControlID="FirstName"DefaultValue=" "Name="FIRST"PropertyName="Text"Type="String"/><asp:ControlParameterControlID="LastName"DefaultValue=" "Name="LAST"PropertyName="Text"Type="String"/><asp:ControlParameterControlID="DOB"DefaultValue=" "Name="DOB"PropertyName="Text"Type="String"/></SelectParameters></asp:SqlDataSource><asp:GridViewID="GridView2"runat="server"AutoGenerateColumns="False"DataSourceID="SqlDataSource2"><Columns><asp:BoundFieldDataField="LAST"HeaderText="LAST"SortExpression="LAST"/><asp:BoundFieldDataField="FIRST"HeaderText="FIRST"SortExpression="FIRST"/><asp:BoundFieldDataField="DOB"HeaderText="DOB"SortExpression="DOB"/><asp:BoundFieldDataField="RAD #"HeaderText="RAD #"SortExpression="RAD #"/><asp:BoundFieldDataField="MR#"HeaderText="MR#"SortExpression="MR#"/><asp:BoundFieldDataField="EXAM#"HeaderText="EXAM#"SortExpression="EXAM#"/><asp:BoundFieldDataField="EXAM DATE"HeaderText="EXAM DATE"SortExpression="EXAM DATE"/><asp:BoundFieldDataField="EXAM NAME"HeaderText="EXAM NAME"SortExpression="EXAM NAME"/><asp:BoundFieldDataField="ORDER DOC"HeaderText="ORDER DOC"SortExpression="ORDER DOC"/><asp:BoundFieldDataField="Column 9"HeaderText="Column 9"SortExpression="Column 9"/></Columns></asp:GridView><asp:SqlDataSourceID="SqlDataSource2"runat="server"ConnectionString="<%$ ConnectionStrings:RADConnectionString3 %>"SelectCommand="SELECT * FROM [Full File through 2006] WHERE ([MR#] = @.column1)"><SelectParameters><asp:ControlParameterControlID="MR"Name="column1"PropertyName="Text"Type="String"/></SelectParameters></asp:SqlDataSource></div><br/><br/>
</form>
</
body></
html>I had a similar situation and solved it using a very cheap method. You might get a better method from someone else.
What I did was that I used to check if the textbox is empty, if it was, then I used to remove that part of the string from the full query string. So its a bunch of if-then to build a query string-
hope this helps,
bullpit
|||I sure hope there is a better way cause i don't know how to do that. LOL Thanks for the help. I will try it not to sure how far i will get though.
|||LIKE as you are using it should match anything that contains the string anywhere. The problem is that the Default Value is a space, so it is only trying to match a first name that contains a space. If you change
<asp:ControlParameterControlID="FirstName"DefaultValue=" "Name="FIRST"PropertyName="Text"Type="String"/>
To This
<asp:ControlParameterControlID="FirstName"DefaultValue=""Name="FIRST"PropertyName="Text"Type="String"/>
It should work for you. That is the same for last name, DOB...
|||Something like this:string qString ="";if(TextBox1.Text.Trim() ==""){string st ="([FIRST] LIKE '%' + @.FIRST + '%') AND ")";if(qString.Contains(st)int i = strWhere.LastIndexOf(st); qString = qString.Remove(i, st.Length); } bullpit|||
Benners_J:
LIKE as you are using it should match anything that contains the string anywhere. The problem is that the Default Value is a space, so it is only trying to match a first name that contains a space. If you change
<asp:ControlParameterControlID="FirstName"DefaultValue=" "Name="FIRST"PropertyName="Text"Type="String"/>
To This
<asp:ControlParameterControlID="FirstName"DefaultValue=""Name="FIRST"PropertyName="Text"Type="String"/>
It should work for you. That is the same for last name, DOB...
I think since it is an AND type query, no matter what you put there, if the AND criteria is not met, it won't show the results.
bullpit
|||That is accurate. If the criteria is not met for any part of the WHERE clause, those records will not be returned. However, LIKE does a pattern match, and the '%' means match anything. The following query will return all records (I just tried in in SQL Server 2005, anyway).
SELECT * FROM [Table] WHERE [FirstName] LIKE('%%')
That is essentially what the query will run if @.FIRST is an empty string "". If @.FIRST contains a space, however, it will only match records where the first name contains a space.
|||Yup, I tried that too after you pointed it out and it works.
Thanks,
bullpit
|||I have tried what yall suggested, but having no luck. Is the below right?
<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:RADConnectionString2 %>"SelectCommand="SELECT * FROM [Full File through 2006] WHERE (([FIRST] LIKE '%%' + @.FIRST + '%%') AND ([LAST] LIKE '%%' + @.LAST + '%%') AND ([DOB] LIKE '%%' + @.DOB + '%%'))"OnSelecting="SqlDataSource1_Selecting"><SelectParameters><asp:ControlParameterControlID="FirstName"DefaultValue=""Name="FIRST"PropertyName="Text"Type="String"/><asp:ControlParameterControlID="LastName"DefaultValue=""Name="LAST"PropertyName="Text"Type="String"/><asp:ControlParameterControlID="DOB"DefaultValue=""Name="DOB"PropertyName="Text"Type="String"/></SelectParameters></asp:SqlDataSource>|||
Why do you have two %s in your query?
bullpit
|||Have your like clause like this:
LIKE '%' +@.FIRST+ '%'
bullpit
|||I thought that was the change that was suggested inYou got confused with this query. He gave this query just to show the difference when there is a blank space in the input field. This is not what he wanted you to implement. He just wanted you to set the default value = "" instead of " ".
SELECT * FROM [Table] WHERE [FirstName] LIKE('%%')
hope this helps,
bullpit
|||Oh i had tried that already that is why there were spaces in there. Have tried it with spaces and without. Still want work.|||I am talking about removing the spaces in the deafult value of the textbox. Are you talking about the same thing?
Monday, March 12, 2012
problems with insert
use inventory
go
CREATE TABLE Job_Title
(Job_Title_Title varchar(25) NOT NULL ,
Job_Title_EEO1_Classification varchar(25) ,
Job_Title_Job_Description Varchar(45) ,
Job_Title_Exempt_Status Varchar(15)
, PRIMARY KEY (Job_Title_Title)
);
CREATE TABLE Employee
(Employee_Emp_ID smallint NOT NULL ,
Employee_last_name varchar(15) ,
Employee_first_name varchar(15) ,
Employee_address varchar(30) ,
Employee_city varchar(15) ,
Employee_state char(2) ,
Employee_Telephone_area_code char(3) ,
Employee_Telephone_number char(8) ,
Employee_EEO1_Classification varchar(25) ,
Employee_Hire_Date varchar(8) ,
Employee_Salary int ,
Employee_Gender Varchar(1) ,
Employee_Age tinyint ,
Employee_Title varchar(25)
, PRIMARY KEY (Employee_Emp_ID)
, constraint Employee2Job_Title FOREIGN KEY (Employee_Title
) REFERENCES Job_Title
);
here is the script i am trying to use to insert my data:
use inventory
go
Insert INTO dbo.Employee Values
(1,'Edelman','Glenn','175 Bishop Lane','La Jolla','CA',619,'555-0199','Sales Workers','10/7/2003',21500,'M',64,'Cashier');
Insert INTO dbo.Employee Values
(2,'McMullen','Eric','762 Church Street','Lemon Grove','CA',619,'555-0133','Sales Workers','11/1/2002',13500,'M',20,'Bagger');
Insert INTO dbo.Employee Values
(3,'Slenj','Raj','123 Torrey Drive','North Clairmont','CA',619,'555-0123','Officials & Managers','6/1/2000',48000,'M',34,'Assistant Manager');
Insert INTO dbo.Employee Values
(4,'Broun','Erin','2045 Parkway Apt 2b','Encinitas','CA',760,'555-0100','Sales Workers','3/12/2003',10530,'F',24,'Bagger - 30 hours/wk');
Insert INTO dbo.Employee Values
(5,'Carpenter','Donald','927 Second Street','Encinitas','CA',619,'555-0154','Office/Clerical','11/1/2003',15000,'M',18,'Stocker');
Insert INTO dbo.Employee Values
(6,'Esquivez','David','10983 North Coast Highway Apt 902','Encinitas','CA',760,'555-0108','Operatives (Semi skilled)','7/25/2003',18500,'M',25,'Asst. - Butchers & Seafood Specialists');
Insert INTO dbo.Employee Values
(7,'Sharp','Nancy','10793 Montecino Road','Ramona','CA',858,'555-0135','Sales Workers','7/12/2003',21000,'F',24,'Cashier');
and here are my errors:
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 3
String or binary data would be truncated.
The statement has been terminated.
Msg 547, Level 16, State 0, Line 5
The INSERT statement conflicted with the FOREIGN KEY constraint "Employee2Job_Title". The conflict occurred in database "Inventory", table "dbo.Job_Title", column 'Job_Title_Title'.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 7
String or binary data would be truncated.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 9
String or binary data would be truncated.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 11
String or binary data would be truncated.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 13
String or binary data would be truncated.
The statement has been terminated.
HelpA couple of things to consider:
First, you have the Employee_Hire_Date defined as a varchar(8) and you are attempting to store 9 characters in it, eg 10/7/2003.
Also, it appears that you are trying to insert an Employee with an Employee_Title that does not have a corresponding row in the Job_Title table.
HTH...
Joe|||well i got every thing fixed except for:
Msg 547, Level 16, State 0, Line 5
The INSERT statement conflicted with the FOREIGN KEY constraint "Employee2Job_Title". The conflict occurred in database "Inventory", table "dbo.Job_Title", column 'Job_Title_Title'.
The statement has been terminated.
still working on this
|||
From the order of your errors earlier, i think this statement is causing the problem:
insert into employee
values (3,'Slenj','Raj','123 Torrey Drive','North Clairmont','CA',619,'555-0123','Officials & Managers','6/1/2000',48000,'M',34,'Assistant Manager')
And as Joe correctly suggested, its because you are trying to add a record to the employees table with a value in Employee_Title which doesn't exist in the Job_Title_Title field in the Job_title table - in this case, Assistant Manager.
To fix the error, you'll just need to add the Assistant Manager record to the Job_Title table.
HTHT!
Yes, the foreign key value(s) (lookup table) must be in place before the primary key row (that refers to the foreign key row) can be added--assuming you have created a PK/FK. No, the entire FK table need not be pre-populated, but that's often how it's done.
hth
|||Well, i finally got it. I did change the field size of the date field to 10, and that helped. i also loaded the jobs table first, and that took care of the key problem.Thanks for all the help, now i must move on to the next phase, so i will probly need more help again soon but i am very happy to get this part finished.
Thanks again! :-)|||So, I have a question for you. Why did you choose a string to handle a DateTime field? Do you plan to write all of your own date validation, artihmetic and parsing routines yourself?
problems with insert
use inventory
go
CREATE TABLE Job_Title
(Job_Title_Title varchar(25) NOT NULL ,
Job_Title_EEO1_Classification varchar(25) ,
Job_Title_Job_Description Varchar(45) ,
Job_Title_Exempt_Status Varchar(15)
, PRIMARY KEY (Job_Title_Title)
);
CREATE TABLE Employee
(Employee_Emp_ID smallint NOT NULL ,
Employee_last_name varchar(15) ,
Employee_first_name varchar(15) ,
Employee_address varchar(30) ,
Employee_city varchar(15) ,
Employee_state char(2) ,
Employee_Telephone_area_code char(3) ,
Employee_Telephone_number char(8) ,
Employee_EEO1_Classification varchar(25) ,
Employee_Hire_Date varchar(8) ,
Employee_Salary int ,
Employee_Gender Varchar(1) ,
Employee_Age tinyint ,
Employee_Title varchar(25)
, PRIMARY KEY (Employee_Emp_ID)
, constraint Employee2Job_Title FOREIGN KEY (Employee_Title
) REFERENCES Job_Title
);
here is the script i am trying to use to insert my data:
use inventory
go
Insert INTO dbo.Employee Values
(1,'Edelman','Glenn','175 Bishop Lane','La Jolla','CA',619,'555-0199','Sales Workers','10/7/2003',21500,'M',64,'Cashier');
Insert INTO dbo.Employee Values
(2,'McMullen','Eric','762 Church Street','Lemon Grove','CA',619,'555-0133','Sales Workers','11/1/2002',13500,'M',20,'Bagger');
Insert INTO dbo.Employee Values
(3,'Slenj','Raj','123 Torrey Drive','North Clairmont','CA',619,'555-0123','Officials & Managers','6/1/2000',48000,'M',34,'Assistant Manager');
Insert INTO dbo.Employee Values
(4,'Broun','Erin','2045 Parkway Apt 2b','Encinitas','CA',760,'555-0100','Sales Workers','3/12/2003',10530,'F',24,'Bagger - 30 hours/wk');
Insert INTO dbo.Employee Values
(5,'Carpenter','Donald','927 Second Street','Encinitas','CA',619,'555-0154','Office/Clerical','11/1/2003',15000,'M',18,'Stocker');
Insert INTO dbo.Employee Values
(6,'Esquivez','David','10983 North Coast Highway Apt 902','Encinitas','CA',760,'555-0108','Operatives (Semi skilled)','7/25/2003',18500,'M',25,'Asst. - Butchers & Seafood Specialists');
Insert INTO dbo.Employee Values
(7,'Sharp','Nancy','10793 Montecino Road','Ramona','CA',858,'555-0135','Sales Workers','7/12/2003',21000,'F',24,'Cashier');
and here are my errors:
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 3
String or binary data would be truncated.
The statement has been terminated.
Msg 547, Level 16, State 0, Line 5
The INSERT statement conflicted with the FOREIGN KEY constraint "Employee2Job_Title". The conflict occurred in database "Inventory", table "dbo.Job_Title", column 'Job_Title_Title'.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 7
String or binary data would be truncated.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 9
String or binary data would be truncated.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 11
String or binary data would be truncated.
The statement has been terminated.
Msg 8152, Level 16, State 14, Line 13
String or binary data would be truncated.
The statement has been terminated.
HelpA couple of things to consider:
First, you have the Employee_Hire_Date defined as a varchar(8) and you are attempting to store 9 characters in it, eg 10/7/2003.
Also, it appears that you are trying to insert an Employee with an Employee_Title that does not have a corresponding row in the Job_Title table.
HTH...
Joe|||well i got every thing fixed except for:
Msg 547, Level 16, State 0, Line 5
The INSERT statement conflicted with the FOREIGN KEY constraint "Employee2Job_Title". The conflict occurred in database "Inventory", table "dbo.Job_Title", column 'Job_Title_Title'.
The statement has been terminated.
still working on this
|||
From the order of your errors earlier, i think this statement is causing the problem:
insert into employee
values (3,'Slenj','Raj','123 Torrey Drive','North Clairmont','CA',619,'555-0123','Officials & Managers','6/1/2000',48000,'M',34,'Assistant Manager')
And as Joe correctly suggested, its because you are trying to add a record to the employees table with a value in Employee_Title which doesn't exist in the Job_Title_Title field in the Job_title table - in this case, Assistant Manager.
To fix the error, you'll just need to add the Assistant Manager record to the Job_Title table.
HTHT!
Yes, the foreign key value(s) (lookup table) must be in place before the primary key row (that refers to the foreign key row) can be added--assuming you have created a PK/FK. No, the entire FK table need not be pre-populated, but that's often how it's done.
hth
|||Well, i finally got it. I did change the field size of the date field to 10, and that helped. i also loaded the jobs table first, and that took care of the key problem.Thanks for all the help, now i must move on to the next phase, so i will probly need more help again soon but i am very happy to get this part finished.
Thanks again! :-)|||So, I have a question for you. Why did you choose a string to handle a DateTime field? Do you plan to write all of your own date validation, artihmetic and parsing routines yourself?
problems with IF @test_var = NULL
this is my procedure but is doesn't work. who can tell me what's wrong?
CREATE PROCEDURE new_procedure
@.test_var int
AS
BEGIN
IF @.test_var = NULL
BEGIN
INSERT INTO table (isnull) VALUES (0)
END
ELSE
BEGIN
INSERT INTO table (isnull) VALUES (1)
END
END
the result of "IF @.test_var = NULL" always seems to be false, because I
only get 1 in the column.
Why does this not work?
thanxFirst of all if would suggest NOT to use reserved snytax word as
columnnames etc. (those one marked as colored in QA :-) ). Second, to
the base problem "= NULL" is NOT the same as "IS NULL" un less you
specify the ANSI_NULLS switch:
SET ANSI_NULLS ON
DECLARE @.test varchar(100)
Select 1 where @.test = NULL
SELECT 1 where @.test is null
GO
SET ANSI_NULLS OFF
DECLARE @.test varchar(100)
Select 1 where @.test = NULL
SELECT 1 where @.test is null
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--|||CREATE PROCEDURE new_procedure
@.test_var int
AS
BEGIN
IF @.test_var is NULL
BEGIN
INSERT INTO table (isnull) VALUES (0)
END
ELSE
BEGIN
INSERT INTO table (isnull) VALUES (1)
END
END|||To add to the other responses, consider simplifying your proc with a CASE
expression:
CREATE PROCEDURE new_procedure
@.test_var int
AS
INSERT INTO MyTable (isnull)
VALUES (CASE WHEN @.test_var IS NULL THEN 0 ELSE 1 END)
GO
Hope this helps.
Dan Guzman
SQL Server MVP
"Rudderius" <dries@.bestopia.be> wrote in message
news:43202221$0$335$ba620e4c@.news.skynet.be...
> hey,
> this is my procedure but is doesn't work. who can tell me what's wrong?
> CREATE PROCEDURE new_procedure
> @.test_var int
> AS
> BEGIN
> IF @.test_var = NULL
> BEGIN
> INSERT INTO table (isnull) VALUES (0)
> END
> ELSE
> BEGIN
> INSERT INTO table (isnull) VALUES (1)
> END
> END
> the result of "IF @.test_var = NULL" always seems to be false, because I
> only get 1 in the column.
> Why does this not work?
> thanx
Friday, March 9, 2012
Problems with duplicate data
CREATE TABLE [dbo].[Applicant] (
[ClientID] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[ApplicantID] [bigint] NOT NULL ,
[PositionID] [int] NOT NULL ,
[JobID] [bigint] IDENTITY (1, 1) NOT NULL ,
[DatePosted] [datetime] NULL ,
[FirstName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[LastName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Email] [varchar] (45) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
I am doing the following from a stored procedure:
INSERT INTO Applicant
(ClientID,ApplicantID,PositionID,FirstNa
me,LastName,Email,DatePosted)
Select @.ClientID,COALESCE(max(ApplicantID),1000
)+1,@.PositionID,@.FirstName,
@.LastName,@.Email,getdate()
from ftsolutions.dbo.Applicant
where ClientID = @.ClientID
I am trying to create 2 unique values here. One is the JobID, which is an
identity field. and an ApplicantID which is just a calculated field.
Normally, this works fine.
But I have found one place where I have 2 records with the same JobIDs
(3736) as well as the same ApplicantID (1013).
Not sure how that happened.
Is if possible for 2 Inserts to grab the same ApplicantID at the same time?
You could fix this (I assume but setting this up as a transaction to lock
the record/table), but I was under the assumption that the Insert does this
implicitly for the duration of the Insert.
Am I wrong here?
Thanks,
TomIn READ COMMITTED isolation level with non-exclusive locking, it is very
possible for two users to get the same value. The two calls would have to
be made almost simultaneously, but if they both read before one starts the
insert process you will get locks.
Here is ~ what each does
Get shared lock on row
READ value
Release shared lock on row
Get Update lock on row
UPDATE row
Release lock on row
So you need to change it to SET ISOLATION LEVEL REPEATABLE READ (so locks
aren't released) and put XLOCK as a hint on that table in the select so no
one else can read.
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"tshad" <tscheiderich@.ftsolutions.com> wrote in message
news:%23hgL1CJYFHA.1092@.tk2msftngp13.phx.gbl...
>I have the following table:
> CREATE TABLE [dbo].[Applicant] (
> [ClientID] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [ApplicantID] [bigint] NOT NULL ,
> [PositionID] [int] NOT NULL ,
> [JobID] [bigint] IDENTITY (1, 1) NOT NULL ,
> [DatePosted] [datetime] NULL ,
> [FirstName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [LastName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [Email] [varchar] (45) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> GO
> I am doing the following from a stored procedure:
> INSERT INTO Applicant
> (ClientID,ApplicantID,PositionID,FirstNa
me,LastName,Email,DatePosted)
> Select @.ClientID,COALESCE(max(ApplicantID),1000
)+1,@.PositionID,@.FirstName,
> @.LastName,@.Email,getdate()
> from ftsolutions.dbo.Applicant
> where ClientID = @.ClientID
> I am trying to create 2 unique values here. One is the JobID, which is an
> identity field. and an ApplicantID which is just a calculated field.
> Normally, this works fine.
> But I have found one place where I have 2 records with the same JobIDs
> (3736) as well as the same ApplicantID (1013).
> Not sure how that happened.
> Is if possible for 2 Inserts to grab the same ApplicantID at the same
> time?
> You could fix this (I assume but setting this up as a transaction to lock
> the record/table), but I was under the assumption that the Insert does
> this implicitly for the duration of the Insert.
> Am I wrong here?
> Thanks,
> Tom
>|||"Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
news:%23kZLjiJYFHA.3732@.TK2MSFTNGP10.phx.gbl...
> In READ COMMITTED isolation level with non-exclusive locking, it is very
> possible for two users to get the same value. The two calls would have to
> be made almost simultaneously, but if they both read before one starts the
> insert process you will get locks.
> Here is ~ what each does
> Get shared lock on row
> READ value
> Release shared lock on row
> Get Update lock on row
> UPDATE row
Why are we using an Update lock? Is that the lock that is always used for
an insert?
> Release lock on row
> So you need to change it to SET ISOLATION LEVEL REPEATABLE READ (so locks
> aren't released) and put XLOCK as a hint on that table in the select so no
> one else can read.
Where do I set this?
Would doing a "begin tran" also solve the problem?
Thanks,
Tom
>
> --
> ----
--
> Louis Davidson - http://spaces.msn.com/members/drsql/
> SQL Server MVP
>
> "tshad" <tscheiderich@.ftsolutions.com> wrote in message
> news:%23hgL1CJYFHA.1092@.tk2msftngp13.phx.gbl...
>|||Inline comments:
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"tshad" <tscheiderich@.ftsolutions.com> wrote in message
news:edXahoJYFHA.2560@.TK2MSFTNGP10.phx.gbl...
> "Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
> news:%23kZLjiJYFHA.3732@.TK2MSFTNGP10.phx.gbl...
> Why are we using an Update lock? Is that the lock that is always used for
> an insert?
Actually what I think technically happens is the UPDATE Lock signals that we
might make an update, then an Exclusive lock is taken after the update and
released after the update is committed.
>
> Where do I set this?
>
SET ISOLATION LEVEL REPEATABLE READ
INSERT INTO Applicant
(ClientID,ApplicantID,PositionID,FirstNa
me,LastName,Email,DatePosted)
Select @.ClientID,COALESCE(max(ApplicantID),1000
)+1,@.PositionID,@.FirstName,
@.LastName,@.Email,getdate()
from ftsolutions.dbo.Applicant (XLOCK)
where ClientID = @.ClientID
> Would doing a "begin tran" also solve the problem?
I would include the BEGIN and COMMIT TRANSACTION statements just to remind
yourself of what is happening, and it will not affect performance.
But, because your statement is already within a transaction since the INSERT
and SELECT are part of the same statement. The problem is that shared locks
are compatible, meaning two different connections can have shared locks on
the same resource, in this case your row with the max(applicationId). This
is why we use the exclusive lock. Then, in READ COMMITTED locks aren't
held, so we up this to REPEATABLE READ, which doesn't allow data to be
deleted out from under us, which it does by not releasing locks (which is
our goal.) Now you can be sure that you won't get collisions.
> Thanks,
> Tom
>|||"Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
news:uxAeq4MYFHA.796@.TK2MSFTNGP10.phx.gbl...
> Inline comments:
> --
> ----
--
> Louis Davidson - http://spaces.msn.com/members/drsql/
> SQL Server MVP
>
> "tshad" <tscheiderich@.ftsolutions.com> wrote in message
> news:edXahoJYFHA.2560@.TK2MSFTNGP10.phx.gbl...
> Actually what I think technically happens is the UPDATE Lock signals that
> we might make an update, then an Exclusive lock is taken after the update
> and released after the update is committed.
> SET ISOLATION LEVEL REPEATABLE READ
> INSERT INTO Applicant
> (ClientID,ApplicantID,PositionID,FirstNa
me,LastName,Email,DatePosted)
> Select @.ClientID,COALESCE(max(ApplicantID),1000
)+1,@.PositionID,@.FirstName,
> @.LastName,@.Email,getdate()
> from ftsolutions.dbo.Applicant (XLOCK)
> where ClientID = @.ClientID
>
> I would include the BEGIN and COMMIT TRANSACTION statements just to remind
> yourself of what is happening, and it will not affect performance.
> But, because your statement is already within a transaction since the
> INSERT and SELECT are part of the same statement. The problem is that
> shared locks are compatible, meaning two different connections can have
> shared locks on the same resource, in this case your row with the
> max(applicationId). This is why we use the exclusive lock. Then, in READ
> COMMITTED locks aren't held, so we up this to REPEATABLE READ, which
> doesn't allow data to be deleted out from under us, which it does by not
> releasing locks (which is our goal.) Now you can be sure that you won't
> get collisions.
>
So the XLOCK is used because a lock isn't normally done on the read part of
the statement. Since we could both read before the lock is instituted for
the insert, we are telling the system to lock the "applicant" table before
doing the select. I assume the lock would then be carried through the whole
statement (select then insert) and be released on exit of the insert
statement.
Just reiterating what you already said to make sure I understand what is
happening.
Thanks,
Tom
>|||> So the XLOCK is used because a lock isn't normally done on the read part
> of the statement. Since we could both read before the lock is instituted
> for the insert, we are telling the system to lock the "applicant" table
> before doing the select. I assume the lock would then be carried through
> the whole statement (select then insert) and be released on exit of the
> insert statement.
Close. The lock is usually taken (so noone will invalidate the row while
SQL Server fetches the data) but not usually held. The lock taken is
usually a SHARED lock, but if we use a shared lock, then more than one
process can read the value at the same time. The exclusive lock means NO
ONE can read or modify the data.
The isolation level tells SQL Server to keep the lock until the transaction
is over.
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"tshad" <tscheiderich@.ftsolutions.com> wrote in message
news:eu0I%23lgYFHA.3164@.TK2MSFTNGP09.phx.gbl...
> "Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
> news:uxAeq4MYFHA.796@.TK2MSFTNGP10.phx.gbl...
> So the XLOCK is used because a lock isn't normally done on the read part
> of the statement. Since we could both read before the lock is instituted
> for the insert, we are telling the system to lock the "applicant" table
> before doing the select. I assume the lock would then be carried through
> the whole statement (select then insert) and be released on exit of the
> insert statement.
> Just reiterating what you already said to make sure I understand what is
> happening.
> Thanks,
> Tom
>|||"Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
news:uhvb4njYFHA.3184@.TK2MSFTNGP15.phx.gbl...
> Close. The lock is usually taken (so noone will invalidate the row while
> SQL Server fetches the data) but not usually held. The lock taken is
> usually a SHARED lock, but if we use a shared lock, then more than one
> process can read the value at the same time. The exclusive lock means NO
> ONE can read or modify the data.
> The isolation level tells SQL Server to keep the lock until the
> transaction is over.
>
On the isolation level, you said to do the following (I assume in my SP),
SET ISOLATION LEVEL REPEATABLE READ
INSERT INTO Applicant
(ClientID,ApplicantID,PositionID,FirstNa
me,LastName,Email,DatePosted)
Select @.ClientID,COALESCE(max(ApplicantID),1000
)+1,@.PositionID,@.FirstName,
@.LastName,@.Email,getdate()
from ftsolutions.dbo.Applicant (XLOCK)
where ClientID = @.ClientID
Is this Level held until I am finished with this connection (SP) or do I
need to change it (and how do I) right after the insert statement?
Thanks,
Tom
> --
> ----
--
> Louis Davidson - http://spaces.msn.com/members/drsql/
> SQL Server MVP
>
> "tshad" <tscheiderich@.ftsolutions.com> wrote in message
> news:eu0I%23lgYFHA.3164@.TK2MSFTNGP09.phx.gbl...
>