Escaping ' For Sql Statement (should Be Really Easy But Its Not Working)

May 21, 2008

     
 
 
myCommand2.CommandText = "INSERT INTO testimonials(name,email,testimonial,approved,time) VALUES ('" + exp.escString(txtName.Text) + "','" + exp.escString(txtEmail.Text) + "','"  +    txtTestimonial.Text + "','" + false + "','" + DateTime.Now + "')";
 
ok the form has a field txtTestimonial.Text 
these strings work when i submit them though
thats all folks
that"s  (double quotes)

 that\"s
that\"s 
 
 
these fail
that's  
that's 

that\'s

that\'s

 tried up to 7 just to make sure

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 's'.
Unclosed quotation mark after the character string ')'.
 I figure the " works because it ends up being ' " ' in the sql statement and it doesnt mind that

I tried researching this. I could not find any info stating that perhaps sql escapes things differently. I was on the assumption that in the sql itself the database would reconise the before the '.
I read i can use html decode but it seems that then i will have to undecode everytime I read from the database and it could be a major pain if I am using a datagrid or something and a big mess.
 
Any help would be greatly appreciated.
 
Jim 
 
 

View 5 Replies


ADVERTISEMENT

If Statement (EASY)

Jan 8, 2007

I'm trying to group ages in one report, and Case numbers in another. Both are in string datatype, and require more then 3 choices. Im not keen on coding, so i was wondering, how do you make an IFF statement with more then 3 choices, i need about 7, maybe even a little more. *this is for a column grouping in a matrix.

Here's what i have right now...It works..but i need to add more years.



=iif(left(Fields!ICNNo.Value, 1) = "4", "2004",

iif(left(Fields!ICNNo.Value, 1) = "5", "2005",

iif(left(Fields!ICNNo.Value, 1) = "6", "2006", "Unknown")))



Please help! thanks!

View 10 Replies View Related

Is It Easy To Amend An Insert Statement.

Jul 30, 2007

I am trying to amend an SQL insert statement but it is not working.
It is as follows can anyone tell me what i am doing wrong.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" DeleteCommand="DELETE FROM [useridTest] WHERE [userID] = @original_userID AND [userName] = @original_userName AND [listCopy] = @original_listCopy"
InsertCommand="INSERT INTO [useridTest] ([userID], [userName], [listCopy]) VALUES (<% user.ProviderUserKey.ToString() %>, @userName, @listCopy)"

View 1 Replies View Related

Select Statement Question !! An Easy One !!

Mar 12, 2005

Im starting to learn SQL at school !!

and would like to do something like this. !! but i just cant figure that out.

i have a table that containes all my categories in it. And as you can see i have "PARENT" and "CHILD" categories.

I would like to get something like this by using a simple SELECT statement !! is it possible...


===============
=#1 PARENT ID NAME=
===============
=#1 CHILD NAME HERE
=#2 CHILD NAME HERE
=#3 CHILD NAME HERE
===============
=#2 PARENT ID NAME=
===============
=#1 CHILD NAME HERE
=#2 CHILD NAME HERE
=#3 CHILD NAME HERE

im not trying to show this in my Query Analyser but on a Web Page by using a datagrid.

View 1 Replies View Related

Easy Table Based Update Statement???

Jul 20, 2005

Hello,I have 2 ways of updating data I'm using often1) via a cursor on TABLE1 update fields in TABLE22) via an some of variables ...SELECT @var1=FLD1, @var2=FLD2 FROM TABLE1 WHERE FLD-ID = @inputVARUPDATE TABLE2SET FLDx = @var1, FLDy = @var2WHERE ...Now I have a system with 2 databases and I need to update table DB2.TABbased on data in DB1.TAB. Instead of using 1 of the 2 ways I normally use,I thought it would be much easier to get the required data immediately fromDB1.TAB in the update-statement of DB2.TAB ... but the way to do thatconfuses me. I've checked books online and a lot of newsgrouppostingsgiving good information but still I keep getting errors like this ...The column prefix 'x.ADS' does not match with a table name or alias nameused in the query.while executing the following statement ...UPDATE DB2.dbo.TABSETFLD1 = x.FLD1,FLD2 = x.FLD2,...FROM DB1.dbo.TAB x, DB2.dbo.ADSWHERE DB2.dbo.TAB.REFID = x.IDOFTAB1 AND DB2.dbo.TAB.IDOFTAB2 =@InputParameterSo in DB2.TAB I have a field REFID reffering to the keyfield IDOFTAB1 oftable DB1.TABAND I only want to update the row in DB2.TAB with the unique keyfieldIDOFTAB2 equal to variable @InputParameterDo you see what I'm doing wrong?--Thank you,Kind regards,Perre Van Wilrijk,Remove capitals to get my real email address,

View 8 Replies View Related

Easy One(?) Converting Sql05 Statement To Work In Sql Express

Feb 7, 2008



Hi, I was handed an old application written for sql05, it has this (kind of) statement:
Dim CommandText As String = "SELECT c.name FROM db1 c LEFT JOIN "

CommandText += "db2.dbo.Users u ON u.iKey = c.key "

CommandText += "WHERE u.cUserName = '" & User & "'"


As you can see, there are two databases, db1 and db2 and this worked fine in sql05, but when I convert each of the databases to sqlexpress, I get this error: Invalid object name 'db2.dbo.Users'.

So how can I make this work in sqlexpress? Are queries across databases not allowed?

Thanks so much for your help!

View 3 Replies View Related

Escaping Single Quotes

Jun 16, 2004

Hi,

I need to have an varchar value with single quotes. For eg: the below code throws compilation error.

Declare @val VARCHAR(20)
SELECT @val = ''+name+''
print @val

Error: Invalid column 'name'


I want to print name enclosed with single quotes. Please guide me.

Regards,
Sam

View 1 Replies View Related

Escaping An Apostrophe In MSSQL

Nov 10, 2006

Hi, i'm having problems executing the followingSET @SQLAH = 'SELECT sub_id WHERE 'SET @SQLAH = @SQLAH + 'VENUE_TYPE = Hotel'EXEC(@SQLAH)Its getting stuck at Hotel. I realise that it should include an apostrophe either side like so:..SET @SQLAH = @SQLAH + 'VENUE_TYPE = 'Hotel' '..But this escapes the string, how would i escape an apostrophe in a string?I thought maybe:SET @SQLAH = @SQLAH + 'VENUE_TYPE = 'Hotel' 'But no joy :confused: Thanks

View 4 Replies View Related

Escaping Characters In SQL SERVER

Mar 29, 2007

Hi,

i have a field VPATH which holds virtual path of files from a .net project. i have created a search for a Library section.

i need to search only those pages which are inside "library" folder.

folder name: library

i tried to create a query using VPATH LIKE '%/library/%'. but it is showing result from all the folders. can anyone help me asap?

mail to :priya.interactive@yahoo.co.in.

View 6 Replies View Related

AND Not Working In My SQL Statement...

Jan 28, 2004

Any ideas why this line is bringing up just titles rather than titles and slogan:

dbsreq = "SELECT data_contents, data_style FROM content WHERE data_language = '" & siaith & "' AND data_type = 'title' AND 'slogan';"

(obviously it's all on one line in my code)

I don't understand why it brings up just 'title', not 'title' and 'slogan'?

Any ideas/fizes/suggestion would be greatfully appreciated.

Thanks,
Deian

View 7 Replies View Related

Like Statement Not Working.

May 8, 2008

I have a stored procedure that has an @Style parameter passed into it.

And down at the very bottom of the procedure it has this line:
And Style Like @Style

Now I realize that is not really valid, and I changed it to Style=@Style. But I'd like to understand WHY that isn't working as it was previously.

On our development box (single core X64) it works fine but on our multiple core X64 production box, this doesn't work.

Any ideas?

This is a MS SQL 2005 server we are talking to.

View 15 Replies View Related

Escaping Quotes In Parameterized Query

Feb 7, 2008

Hi,

I have a parameterized query. The parameters contain data from my tables. Some of the parameters could include single quotes. The single quotes are wreaking havoc in my parameterized query. How can I replace single quotes with double quotes inside of my SQL stored
procedure?

I know that it's something similar to REPLACE(@variablename, '''''', ''''''''), but I can't get the number of quotes right.

All of the examples that I am seeing are converting the quotes inside of an application. This is not an option for me, as I am calling this stored procedure from a SQL job that will run daily.

Thx.

View 2 Replies View Related

Escaping Data For Update Query

Jun 4, 2007

I have some code (C#) that runs an SQL update query that sets thevalue of a column to what the user passes. So, this causes an errorwhen anything the user passes in has a ' character in it. I'm surethere's other characters that'll break it too. So, I was wondering,how do I get around this? Is there some commonly accepted regexpattern that will make the value safe to run in an SQL query? How canI take care of any values that need to be escaped?I'm not using any fancy ado.net objects:string sql= [whatever the user passes in]SqlConnection connection = newSqlConnection(ConfigurationManager.ConnectionStrin gs[Utils.GetConnectionString].ToString());connection.Open();SqlCommand command = connection.CreateCommand();command.CommandType = CommandType.Text;command.CommandText = sql;try{int result = command.ExecuteNonQuery();if (result != 1){Response.StatusCode = 500;Response.Write("The file has been uploaded, but wecould not update the DB");Response.End();}}catch (InvalidOperationException){Response.Clear();Response.Write("error");Response.StatusCode = 500;Response.End();}connection.Close();

View 2 Replies View Related

HELP--UPDATE STATEMENT NOT WORKING

Mar 21, 2000

Hi,

I am trying to write an update query to update rows in one table.

Structure of Table1:

SocialSecurityNumber Varchar(9) -- Primary Key
Name Varchar(30)

Structure of Table2 :

SocialSecurityNumber Varchar(9)
Name Varchar(30)

Table 1 contains:

Row1: "123456789" Sally
Row2: "999999999" Bill
Row3: "333333333" Alex

Table 2 contains:

Row1: "123456789" <NULL>
Row2: "123456789" <NULL>

Basically I want to update the name column in Table 2 (based on the SocialSecurityNumber column) so that after
the update Table 2 will contain:

Row1: "123456789" Sally
Row2: "123456789" Sally
------------------------------------------------------------
First I tried:

UPDATE Table2
INNER JOIN Table1 ON Table2.SocialSecurityNumber = Table1.SocialSecurityNumber
SET Table2.Name = Table1.Name
WHERE Table2.SocialSecurityNumber = Table1.SocialSecurityNumber

This works in Access but not it SQL Server 7.0.
------------------------------------------------------------
Then I tried:

UPDATE Table2
INNER JOIN Table1 ON Table2.SocialSecurityNumber = Table1.SocialSecurityNumber
SET Table2.Name = Table1.Name

Again this works in Access but not it SQL Server 7.0.
------------------------------------------------------------
Finally I tried:

UPDATE Table2, Table1
SET Table2.Name = Table1.Name
WHERE Table2.SocialSecurityNumber = Table1.SocialSecurityNumber

This also did not work.
------------------------------------------------------------
Is there any way to write this update statement without cursors?

Thanks.

View 1 Replies View Related

Insert Statement Not Working

Jun 16, 2006

I have this statement buried in a sproc:


INSERT INTO PLAN_DEMAND ([YEAR], BOD_INDEX, SCEN_ID)
SELECT PLAN_SHIP.[YEAR], PLAN_SHIP.BOD_INDEX, 1
FROM PLAN_SHIP LEFT JOIN PLAN_DEMAND ON
PLAN_SHIP.[YEAR]=PLAN_DEMAND.[YEAR]
AND PLAN_SHIP.[BOD_INDEX]=PLAN_DEMAND.BOD_INDEX
WHERE PLAN_DEMAND.BOD_INDEX IS NULL


When I run the sproc in QA, the statements returns records to the grid, but does not insert them into the table. If I just copy the statement into QA and execute it, it works fine.

I'm sure it's something obvious (but not to me).

Any help would be much appreciated.

View 7 Replies View Related

Print Statement Not Working...

Jun 2, 2008

Hi,

Mine Below Query is not Printing Anything though there is a matching record in table "gpcb_proj_paras"

Can any one help me??

declare @catg as char(1)
set @catg = '''A'''

declare @qry as nvarchar(3000)
declare @paras as varchar(200)


Set @paras = (Select convert(nvarchar(200), app_paras) from gpcb_proj_paras t
where t.act = @catg)

print @paras


-- Regards
Prashant Hirani

View 2 Replies View Related

Update Statement Not Working

Oct 2, 2007

I have the following update statement, which when executed, updates zero rows. However, if I replace the first two lines with a SELECT * , I will get records. Can somebody tell me why?


UPDATE [DW_DatamartDB]. [dbo].[FactLaborDollars]

SET [LaborBudget_USD] = Week1

FROM [DW_StagingDB].[ETL].[Transform_FactLaborBudget] BUDGET JOIN

[DW_StagingDB].[ETL].[Transform_FactLaborDollars] LABOR ON

Labor.Location_Code = Budget.Location_Code

JOIN [DW_DatamartDB]. [dbo].[DimDate] DATE ON

Date.FiscalWeekOfPeriod = Labor.FiscalWeekOfPeriod AND

Date.FiscalPeriodOfYear = Labor.FiscalPeriodOfYear

WHERE Labor.FiscalYear = CAST(SUBSTRING(DATE.Date_Code,1,4) AS NVARCHAR(50)) AND

Budget.FiscalYear = CAST(SUBSTRING(DATE.Date_Code,4,1) AS NVARCHAR(50)) AND

Date.FiscalWeekofYear = 1

View 6 Replies View Related

RECEIVE Statement Not Working

Nov 19, 2007

I followed an example using the AdventureWorks database to set up a simple messaging test on one database:




Code Block
-- We will use adventure works as the sample database
USE AdventureWorks
GO
-- First, we need to create a message type. Note that our message type is
-- very simple and allowed any type of content
CREATE MESSAGE TYPE JobRequest
VALIDATION = NONE
GO
-- Once the message type has been created, we need to create a contract
-- that specifies who can send what types of messages
CREATE CONTRACT JobRequestor
(JobRequest SENT BY INITIATOR)
GO
-- The communication is between two endpoints. Thus, we need two queues to
-- hold messages
CREATE QUEUE RequestorQueue
CREATE QUEUE ReceiverQueue
GO
-- Create the required services and bind them to be above created queues
CREATE SERVICE Requestor
ON QUEUE RequestorQueue
CREATE SERVICE Receiver
ON QUEUE ReceiverQueue (JobRequestor)
GO
-- At this point, we can begin the conversation between the two services by
-- sending messages
DECLARE @conversationHandle UNIQUEIDENTIFIER
DECLARE @message NVARCHAR(100)
BEGIN
BEGIN TRANSACTION;
BEGIN DIALOG @conversationHandle
FROM SERVICE Requestor
TO SERVICE 'Receiver'
ON CONTRACT JobRequestor
WITH ENCRYPTION=OFF, LIFETIME= 600;
-- Send a message on the conversation
SET @message = N'Hello, World';
SEND ON CONVERSATION @conversationHandle
MESSAGE TYPE JobRequest (@message)
COMMIT TRANSACTION
END
GO
-- Receive a message from the queue
RECEIVE CONVERT(NVARCHAR(max), message_body) AS message
FROM ReceiverQueue
-- Cleanup
DROP SERVICE Sender
DROP SERVICE Receiver
DROP QUEUE SenderQueue
DROP QUEUE ReceiverQueue
DROP CONTRACT HelloContract
DROP MESSAGE TYPE HelloMessage
GO


This all works fine but if I run the section that creates the message and then copy the RECEIVE section to a new query window and execute it, nothing is returned. If I run the RECEIVE section within the same query window it returns the 'Hello World' message as expected. I am new to Service Broker and so am assuming that I am missing something obvious!!

View 5 Replies View Related

Update Statement Not Working

Apr 11, 2006

I've got the following update statement:

UPDATE ISSUE_ACTIONS
SET BAE_FLAG = 2
WHERE IA_ISSUE_NO = 399
AND IA_SEQUENCE = 20

The fields BAE_FLAG, IA_ISSUE_NO, and IA_SEQUENCE are all of the type int.

When I run this code inside of my windows app (C#),

cmd3.CommandText = "UPDATE ISSUE_ACTIONS " +
"SET BAE_FLAG = 2 " +
"WHERE IA_ISSUE_NO = 437 " +
"AND IA_SEQUENCE = 13";

try
{
cmd3.ExecuteNonQuery();
}
catch (Exception e)
{
throw (e);
}

I get a timeout error:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.

But when I run the SAME statement from Query Analyzer, it executes without a problem.

Has anyone run into this issue before? How do I get around this?

The CommandTimeout property of cmd3 is set to the default because this is not a complex query and should not take more than .5 seconds to execute.

View 5 Replies View Related

Escaping International (unicode) Characters In String

May 29, 2007

Y'all:I am needing some way, in the SQL Server dialect of SQL, to escape unicodecode points that are embedded within an nvarchar string in a SQL script,e.g. in Java I can do:String str = "This is au1245 test.";in Oracle's SQL dialect, it appears that I can accomplish the same thing:INSERT INTO TEST_TABLE (TEST_COLUMN) VALUES ('This is a1245 test.");I've googled and researched through the MSDN, and haven't discovered asimilar construct in SQL Server. I am already aware of the UNISTR()function, and the NCHAR() function, but those aren't going to work well ifthere are more than a few international characters embedded within astring.Does anyone have a better suggestion?Thanks muchly!GRB-----------------------------------------------------------------------Greg R. Broderick Join Bytes!A. Top posters.Q. What is the most annoying thing on Usenet?---------------------------------------------------------------------

View 3 Replies View Related

There's Just No Escaping It... Data Containing Quotes Ruining CSV Files

Jul 11, 2006

Much to my surprise and dismay, after burning hours and hours developing various SSIS packages to extract data from my SQL 2005 DB to CSV flat files, I found out the hard way that SSIS doesn't properly escape quotes (") in the data (my output file is required to have quotes as text qualifiers).

It seems like I'm pretty much forced to create derived columns to test for the existence of quotes in my data, then either escape them or replace them with another character.

This is really NOT COOL. Not only will this significantly hinder performance, it makes my packages a heck of a lot more complicated (especially when I'm exporting lots of text columns).

Am I doing something wrong, or does SSIS really not escape the text qualifier in a delimited flat file? If so, someone PLEASE tell me this will be fixed in the very near future.

View 21 Replies View Related

(URgent) My Update Statement Is Not Working..

Dec 17, 2007

Hi..
I have inserted couple of data in a particular table which is as follows..
Portfolio Table
PortId PlanId  PortfolioName                           PorfolioDescription  ClientPortolioId




771
17838
BALPORT                                           
NULL
NULL

772
17838
HIGHGROW                                          
NULL
NULL

773
17838
MODGROW                                           
NULL
NULLMy FundDBF is as follows
 RowNumber  FUND_ID            f.ASSETDESC                    Import




20
BALPORT        
              
Balanced                                      
True

21
MODGROW        
              
Moderate Growth                               
True

22
HIGHGROW       
              
High Growth                                   
True
and this is my Update statement UPDATE
Statements..PlanPortfolio
SET
PlanId = pm.PlanId,
PortfolioName = pm.FUND_ID,
PortfolioDescription = pm.ASSETDESC
FROM
Statements..PlanPortfolio p
Join (
SELECT DISTINCT
p.PlanId,
pd.FUND_ID,
f.ASSETDESC ---pd.FUND_ID
FROM
PartDBF pd
INNER JOIN Statements..ClientPlan p
on pd.PLAN_NUM = p.ClientPlanId
INNER JOIN FundDBF f
on pd.FUND_ID = f.FUND_ID
WHERE
pd.Import = 1
AND NOT (
pd.FUND_ID IS NULL
OR
Len(pd.FUND_ID) = 0
OR
pd.FUND_ID NOT IN (
SELECT
PortfolioName
FROM
Statements..PlanPortfolio pp
Where
pp.PlanId = p.PlanId
)
)
) pm
on p.PlanId = pm.PlanId
 
I am trying to put the above table with f,AssetDesc in the PorfolioDescription field..
Any help will be appreciated..
Regards
Karen

View 17 Replies View Related

Delete Statement With Parameters Not Working

Jun 13, 2008

When I debug my code I see the string going into the parameter correclty, but the the delete statement doesnt work and I'm not sure why. Does this look ok?  // Set up SqlCommand, connection to db, sql statement, etc.
SqlCommand DeleteCommand = new SqlCommand();
DeleteCommand.Connection = DBConnectionClass.myConnection;
DeleteCommand.CommandType = CommandType.Text;

// Store Primary Key photoID passed here from DeleteRows_Click
// in a parameter for DeleteCommand
SqlParameter DeletePrimaryKeyParam = new SqlParameter();
DeletePrimaryKeyParam.ParameterName = "@PhotoID";
DeletePrimaryKeyParam.Value = photoID.ToString();

// Insert new parameter into command object
DeleteCommand.Parameters.Add(DeletePrimaryKeyParam);

// Delete row, open connection, execute, close connection
DeleteCommand.CommandText = "Delete From Photo_TBL where PhotoID IN (@PhotoID)";
Response.Write(DeleteCommand.CommandText);
// DeleteCommand.Connection.Close();
DeleteCommand.Connection.Open();
DeleteCommand.ExecuteNonQuery();
DeleteCommand.Connection.Close(); 
 

View 9 Replies View Related

Complex Update Statement Not Working

Nov 6, 2006

hi.

can somebody explain to me why the below
update fails to update one row and updates
the entire table?


Code:


UPDATE addlist
SET add_s = 1
WHERE EXISTS
(SELECT a.add_s, a.email_address, e.public_name
FROM add a, edit e
WHERE a.email_address = e.email_address
and a.add_email = 'mags23@rice.edu' and a.add_s = 0 and e.public_name = 'professor');



and, what is the solution? thank you.

View 8 Replies View Related

Like Statement Is Not Working When I Pass A String

Mar 23, 2008

Hi,
I have a textbox,in which I am allowing user to write the username starting with,user should enter minimum 3 characters, atleast,and when they enter that information, all the names starting with those 3 characters shouls be shown.can any one help me in this.


my query is:

"select username from registration where username like '" + TextBox1.Text + "%'";

It is working with one char,but if I write more than one character in the textbox,it is not creating any error but it is not returning the result.


View 2 Replies View Related

SQL Server 2012 :: How To Stop Select For XML Explicit From Escaping Inner

Jun 3, 2014

I'm working on a script to produce XML. There are two parts to the XML: an envelope (called "message") and a payload ("payload). Here's an example of what the result should look like:

<?xml version="1.0" encoding="utf-8" ?>
<message guid="cb9f7927-a4c7-44f8-9e55-bd5dd3e85894">
<client name="BNS CASL Client" guid="3dc500f3-dffb-455f-a071-12c4fa37a1eb" endPoint="http://localhost:51873/CASLWS.aspx" />
<payload>
<![CDATA[

[code]....

(Note that I had to add a space between the '&' and 'lt' and 'gt' to get it to post in the forum without the forum converting them back to < and >!)You can see that SQL escaped the < and >. Also the CDATA escape sequence is missing.I want to see < instead of & lt and > instead of & gt. Also, I need the CDATA escape sequence.

View 5 Replies View Related

Escaping Bitwise In Full Text Search 2005

Feb 6, 2007

Hi,

We are facing a problem while passing a string containing the "&" character into Full Text search CONTAINS predicate. The records that do have this character are not being returned by the search.

I'd like to raise two questions:

1) Is there any special way to escape this character?
2) Does FTS index it at all?

We have tried all known (to us) ways of escaping like doubling the character, using char(38), using ESCAPE etc..Nothing seem to work. Any help would be appreciated.

Thanks,
Alex

View 2 Replies View Related

Escaping Single Quote In Stored Proc With Parameter..

Feb 26, 2008

We have a .NET drop down, which gets populated as the user types in letters(last name). If the user types in the single quote we get the error about not escaping the single quote. Question is, which way would it be easier to fix, in the .NET code or in the SQL procedure? I am not to sure if we have full access to the source code since that is a 3rd party control, so if that is not feasible how would I fix that in the stored procedure? This is the current proc that we are using:




Code Snippet
select @str = 'SELECT DISTINCT TOP ' + @Top + ' e.DisplayName
as DbComboText,
e.EmployeeID as DbComboValue
FROM DepartmentDirectory.dbo.Employees ee
INNER JOIN DataMart.dbo.Employees e ON ee.UIN = e.UIN
WHERE e.LastName like ''' + @LastName + ''' AND e.FirstName like ''' + @FirstName + '''
ORDER BY e.DisplayName'




Any help is greatly appreciated.

View 5 Replies View Related

T-SQL (SS2K8) :: Update With Case Statement Not Working?

May 29, 2014

I have a situation where I want to update a column if and only if it is null.

UPDATE Employee
SET VEmployeeID = CASE WHEN E.VEmployeeID IS NULL
THEN ves.VEmployeeID
END
FROM Employee E
INNER JOIN VEmployeeStaging VES
ON E.EID= VES.EID

But what happens is when I run the procedure every other time I run it, it changes everything to null. The other times it puts the VEmployeeID in.

So what is happening is the times when it is not null (where it is not supposed to do anything) it puts a null in. The next time it works.

View 6 Replies View Related

Transact SQL :: Insert On Merge Statement Not Working

Oct 7, 2015

In a t-sql 2012 merge statement that is listed below, the insert statement on the merge statement listed below is not working. The update statement works though.

Merge test.dbo.LockCombination AS LKC1
USING
(select LKC.lockID,LKC.seq,A.lockCombo1,A.schoolnumber
from
[Inputtb] A
JOIN test.dbo.School SCH ON A.schoolnumber = SCH.type
JOIN test.dbo.Locker LKR ON SCH.schoolID = LKR.schoolID AND A.lockerNumber = LKR.number
 
[code]...

Thus would you tell me what I need to do to make the insert statement work on the merge statement listed above?

View 10 Replies View Related

SQL Server 2012 :: Insert Not Working On Merge Statement

Oct 7, 2015

In a t-sql 2012 merge statement that is listed below, the insert statement on the merge statement listed below is not working. The update statement works though.

Merge test.dbo.LockCombination AS LKC1
USING
(select LKC.lockID,LKC.seq,A.lockCombo1,A.schoolnumber
from
[Inputtb] A
JOIN test.dbo.School SCH ON A.schoolnumber = SCH.type

[Code] ....

Thus would you tell me what I need to do to make the insert statement work on the merge statement listed above?

View 6 Replies View Related

My Update Statement Isn't Working But Select And Insert Are. What's Wrong?

Aug 11, 2007



here is my code:


Dim cn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("LocalSqlServer").ToString())

cn.Open()

Dim adapter1 As New System.Data.SqlClient.SqlDataAdapter()

adapter1.SelectCommand = New Data.SqlClient.SqlCommand("update aspnet_Membership_BasicAccess.Products
set id = '" & textid.Text & "', name = '" & textname.Text & "', price = '" & textprice.Text & "', description = '" &
textdescription.Text & "', count = '" & textcount.Text & "', pictureadd = '" & textpictureadd.Text & "', artist = '" &textartist.Text & "', catergory = '" & textcategory.text & "' where id = " & Request.Item("id") & ";", cn)

cn.Close()

Response.Redirect("database.aspx")

it posts and the page loads but the data is still the same in my datagrid. what could be wrong with this simple statement... i've tried testing the statement above with constant values of the correct type but i don't think that matters because the SqlCommand() accepts a string only anyways.. doesn't it?

View 5 Replies View Related

Stored Procedure Version Of SELECT Statement - Can't Understand Why It's Not Working

Apr 25, 2006

Hi,
[I'm using VWD Express (ASP.NET 2.0)]
Please help me understand why the following code, containing an inline SQL SELECT query (in bold) works, while the one after it (using a Stored Procedure) doesn't:

<asp:DropDownList ID="ddlContacts" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource2"

DataTextField="ContactNameNumber" DataValueField="ContactID" Font-Names="Tahoma"
Font-Size="10pt" OnDataBound="ddlContacts_DataBound" OnSelectedIndexChanged="ddlContacts_SelectedIndexChanged" Width="218px">
</asp:DropDownList>&nbsp;<asp:Button ID="btnImport" runat="server" Text="Import" />
<asp:Button ID="Button2" runat="server" OnClick="btnNewAccount_Click" Text="New" />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ICLConnectionString %>"
SelectCommand="SELECT Contacts.ContactID, Contacts.ContactLastName + ', ' + Contacts.ContactFirstName + ' - ' + Contacts.ContactNumber AS ContactNameNumber FROM Contacts INNER JOIN AccountContactLink ON Contacts.ContactID = AccountContactLink.ContactID WHERE (AccountContactLink.AccountID = @AccountID) ORDER BY ContactNameNumber">
<SelectParameters>
<asp:ControlParameter ControlID="ddlAccounts" Name="AccountID" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved