Insert In SQL Server C# Code

Feb 7, 2005

When someone clicks my form


i use this code to enter data in Server:





private void Submit_Click(object sender, System.EventArgs e)


{


SqlConnection con = null;


SqlCommand cmd = null;


SqlDataReader rd = null;





try


{


con = new SqlConnection("server=localhost; uid=sa; pwd=123; database=TaskManagement");


cmd = new SqlCommand("INSERT INTO TASK_TYPE (name) VALUES ("+name.Text+")", con);





con.Open();


rd = cmd.ExecuteQuery();








}


catch (Exception e)


{


Response.Write("<p><font color="red">Error: ");


Response.Write(e.Message);


Response.Write("</font></p>");


}


finally


{


if(rd != null)


rd.Close();


if(con != null)


con.Close();


}


}








is that right? I am new in c# and i try to make it work!


Thanks in advance!

View 2 Replies


ADVERTISEMENT

SQL Server Insert Update Stored Procedure - Does Not Work The Same Way From Code Behind

Mar 13, 2007

All:
 I have created a stored procedure on SQL server that does an Insert else Update to a table. The SP starts be doing "IF NOT EXISTS" check at the top to determine if it should be an insert or an update.
When i run the stored procedure directly on SQL server (Query Analyzer) it works fine. It updates when I pass in an existing ID#, and does an insert when I pass in a NULL to the ID#.
When i run the exact same logic from my aspx.vb code it keeps inserting the data everytime! I have debugged the code several times and all the parameters are getting passed in as they should be? Can anyone help, or have any ideas what could be happening?
Here is the basic shell of my SP:
CREATE PROCEDURE [dbo].[spHeader_InsertUpdate]
@FID  int = null OUTPUT,@FLD1 varchar(50),@FLD2 smalldatetime,@FLD3 smalldatetime,@FLD4 smalldatetime
AS
Declare @rtncode int
IF NOT EXISTS(select * from HeaderTable where FormID=@FID)
 Begin  begin transaction
   --Insert record   Insert into HeaderTable (FLD1, FLD2, FLD3, FLD4)    Values (@FLD1, @FLD2, @FLD3,@FLD4)   SET @FID = SCOPE_IDENTITY();      --Check for error   if @@error <> 0    begin     rollback transaction     select @rtncode = 0     return @rtncode    end   else    begin     commit transaction     select @rtncode = 1     return @rtncode    end      endELSE
 Begin  begin transaction
   --Update record   Update HeaderTable SET FLD2=@FLD2, FLD3=@FLD3, FLD4=@FLD4    where FormID=@FID;
   --Check for error   if @@error <> 0    begin     rollback transaction     select @rtncode = 0     return @rtncode    end   else    begin     commit transaction     select @rtncode = 2     return @rtncode   end
End---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
 Thanks,
Blue.

View 5 Replies View Related

Insert :) I Have Different Insert Code Lines (2 Insert Codelines) Which One Best ?

Jun 4, 2008

hello friends
my one insert code lines is below :) what does int32 mean ? AND WHAT IS DIFFERENT BETWEEN ONE CODE LINES AND SECOND CODE LINES :)Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Dim cmd As New SqlCommand("Insert into table1 (UserId) VALUES (@UserId)", conn)
'you should use sproc instead
cmd.Parameters.AddWithValue("@UserId", textbox1.text)
'your value
Try
conn.Open()Dim rows As Int32 = cmd.ExecuteNonQuery()
conn.Close()Trace.Write(String.Format("You have {0} rows inserted successfully!", rows.ToString()))
Catch sex As SqlExceptionThrow sex
Finally
If conn.State <> Data.ConnectionState.Closed Then
conn.Close()
End If
End Try
MY SECOND INSERT CODE LINES IS BELOWDim SglDataSource2, yeni As New SqlDataSource()
SglDataSource2.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString
SglDataSource2.InsertCommandType = SqlDataSourceCommandType.Text
SglDataSource2.InsertCommand = "INSERT INTO urunlistesi2 (kategori1) VALUES (@kategori1)"
SglDataSource2.InsertParameters.Add("kategori1", kategoril1.Text)Dim rowsaffected As Integer = 0
Try
rowsaffected = SglDataSource2.Insert()Catch ex As Exception
Server.Transfer("yardim.aspx")
Finally
SglDataSource2 = Nothing
End Try
If rowsaffected <> 1 ThenServer.Transfer("yardim.aspx")
ElseServer.Transfer("urunsat.aspx")
End If
 
 
cheers

View 2 Replies View Related

Help With Converting Code: VB Code In SQL Server 2000-&&>Visual Studio BI 2005

Jul 27, 2006

Hi all--I'm trying to convert a function which I inherited from a SQL Server 2000 DTS package to something usable in an SSIS package in SQL Server 2005. Given the original code here:
Function Main()
on error resume next
dim cn, i, rs, sSQL
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"
set rs = CreateObject("ADODB.Recordset")
set rs = DTSGlobalVariables("SQLstring").value

for i = 1 to rs.RecordCount
sSQL = rs.Fields(0).value
cn.Execute sSQL, , 128 'adExecuteNoRecords option for faster execution
rs.MoveNext
Next

Main = DTSTaskExecResult_Success

End Function

This code was originally programmed in the SQL Server ActiveX Task type in a DTS package designed to take an open-ended number of SQL statements generated by another task as input, then execute each SQL statement sequentially. Upon this code's success, move on to the next step. (Of course, there was no additional documentation with this code. :-)

Based on other postings, I attempted to push this code into a Visual Studio BI 2005 Script Task with the following change:

public Sub Main()

...

Dts.TaskResult = Dts.Results.Success

End Class

I get the following error when I attempt to compile this:

Error 30209: Option Strict On requires all variable declarations to have an 'As' clause.

I am new to Visual Basic, so I'm on a learning curve here. From what I know of this script:
- The variables here violate the new Option Strict On requirement in VS 2005 to declare what type of object your variable is supposed to use.

- I need to explicitly declare each object, unless I turn off the Option Strict On (which didn't seem recommended, based on what I read).

Given this statement:

dim cn, i, rs, sSQL

I'm looking at "i" as type Integer; rs and sSQL are open-ended arrays, but can't quite figure out how to read the code here:

Set cn = CreateObject("ADODB.Connection")

cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"

set rs = CreateObject("ADODB.Recordset")

This code seems to create an instance of a COM component, then pass provider information and create the recordset being passed in by the previous task, but am not sure whether this syntax is correct for VS 2005 or what data type declaration to make here. Any ideas/help on how to rewrite this code would be greatly appreciated!

View 7 Replies View Related

SQL 2005 Insert Code Help Required

Dec 21, 2007

Hi I am trying to inset data to my sql 2005 database using a webform.. the code I have is
  3    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 4    5    ConnectionString="<%$ ConnectionStrings:SQL2005440975 %>" 6    7    InsertCommand="INSERT INTO [dbo.asp.net_Addresstbl] ([Salutation], [fname], [sname], [Daydb], [Monthdb], [Yeardb], [txtOrg], [txtLine1], [txtLine2], [txtLine3], [txtTown], [txtPostcode], [UserID]) 8    9    VALUES (@Salutation, @fname, @sname, @Daydb, @Monthdb, @Yeardb, @txtOrg, @txtLine1, @txtLine2, @txtLine3, @txtTown, @txtPostcode, @UserID)" 10   11   <InsertParameters>12                                           <asp:FormParameter FormField="Salutation" Name="Salutation" Type="String" />13                                           <asp:FormParameter FormField="fname" Name="fname" Type="String" />14                                           <asp:FormParameter FormField="sname" Name="sname" Type="String" />15                                           <asp:FormParameter FormField="Daydb" Name="Daydb" Type="Decimal" />16                                           <asp:FormParameter FormField="Monthdb" Name="Monthdb" Type="String" />17                                           <asp:FormParameter FormField="Yeardb" Name="Yeardb" Type="Decimal" />18                                           <asp:FormParameter FormField="txtOrg"Name="txtOrg" Type="String" />19                                           <asp:FormParameter FormField="txtLine1" Name="txtLine1" Type="String" />20                                           <asp:FormParameter FormField="txtLine2" Name="txtLine2" Type="String" />21                                           <asp:FormParameter FormField="txtLine3" Name="txtLine3" Type="String" />22                                           <asp:FormParameter FormField="txtTown" Name="txtTown" Type="String" />23                                           <asp:FormParameter FormField="txtPostcode"Name="txtPostcode" Type="String" />24                                           <asp:FormParameter FormField="UserID" Name="UserID" Type="Object" />25   </InsertParameters>26   </asp:SqlDataSource>27   28   <asp:DropDownList ID="Salutation" runat="server" ValidationGroup="Address">29                                   <asp:ListItem>Choose One</asp:ListItem>30                                   <asp:ListItem>Mr.</asp:ListItem>31                                   <asp:ListItem>Mrs.</asp:ListItem>32                                   <asp:ListItem>Ms.</asp:ListItem>33                                   <asp:ListItem>Miss.</asp:ListItem>34                                   <asp:ListItem>Rev.</asp:ListItem>35                                   <asp:ListItem>Doc.</asp:ListItem>36                                   <asp:ListItem>Other.</asp:ListItem>37                               </asp:DropDownList>38   39   <asp:TextBox ID="fname" runat="server" CausesValidation="True"></asp:TextBox>40   41   <asp:TextBox ID="sname" runat="server" CausesValidation="True"></asp:TextBox>42   43   <asp:DropDownList ID="Daydb" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">44                                   <asp:ListItem>Day</asp:ListItem>45                                   <asp:ListItem>01</asp:ListItem>46                                   <asp:ListItem>02</asp:ListItem>47                                   <asp:ListItem>03</asp:ListItem>48                                   <asp:ListItem>04</asp:ListItem>49                                   <asp:ListItem>05</asp:ListItem>50                                   <asp:ListItem>06</asp:ListItem>51                                   <asp:ListItem>07</asp:ListItem>52                                   <asp:ListItem>08</asp:ListItem>53                                   <asp:ListItem>09</asp:ListItem>54                                   <asp:ListItem>10</asp:ListItem>55                                   <asp:ListItem>11</asp:ListItem>56                                   <asp:ListItem>12</asp:ListItem>57                                   <asp:ListItem>13</asp:ListItem>58                                   <asp:ListItem>14</asp:ListItem>59                                   <asp:ListItem>15</asp:ListItem>60                                   <asp:ListItem>16</asp:ListItem>61                                   <asp:ListItem>17</asp:ListItem>62                                   <asp:ListItem>18</asp:ListItem>63                                   <asp:ListItem>19</asp:ListItem>64                                   <asp:ListItem>20</asp:ListItem>65                                   <asp:ListItem>21</asp:ListItem>66                                   <asp:ListItem>22</asp:ListItem>67                                   <asp:ListItem>23</asp:ListItem>68                                   <asp:ListItem>24</asp:ListItem>69                                   <asp:ListItem>25</asp:ListItem>70                                   <asp:ListItem>26</asp:ListItem>71                                   <asp:ListItem>27</asp:ListItem>72                                   <asp:ListItem>28</asp:ListItem>73                                   <asp:ListItem>29</asp:ListItem>74                                   <asp:ListItem>30</asp:ListItem>75                                   <asp:ListItem>31</asp:ListItem>76                               </asp:DropDownList>77   78   <asp:DropDownList ID="Monthdb" runat="server" style="text-align: left">79                                   <asp:ListItem>Month</asp:ListItem>80                                   <asp:ListItem>January</asp:ListItem>81                                   <asp:ListItem>February</asp:ListItem>82                                   <asp:ListItem>March</asp:ListItem>83                                   <asp:ListItem>April</asp:ListItem>84                                   <asp:ListItem>May</asp:ListItem>85                                   <asp:ListItem>June</asp:ListItem>86                                   <asp:ListItem>July</asp:ListItem>87                                   <asp:ListItem>August</asp:ListItem>88                                   <asp:ListItem>September</asp:ListItem>89                                   <asp:ListItem>October</asp:ListItem>90                                   <asp:ListItem>November</asp:ListItem>91                                   <asp:ListItem Value="12">December</asp:ListItem>92                               </asp:DropDownList>93   94   <asp:DropDownList ID="Yeardb" runat="server" style="text-align: left" 95                                   OnSelectedIndexChanged="Year_SelectedIndexChanged" 96                                   DataSourceID="YearDataSource" DataTextField="Year" DataValueField="Year">97                                   <asp:ListItem Selected="True">Choose Year..</asp:ListItem>98   </asp:DropDownList>99         <asp:AccessDataSource ID="YearDataSource" runat="server" 100        DataFile="~/App_Data/year.mdb" SelectCommand="SELECT [Year] FROM [Year]">101        </asp:AccessDataSource>102                          103  <asp:TextBox ID="txtFind" runat="server" CausesValidation="True" ValidationGroup="address"></asp:TextBox>104  105  <asp:Button ID="btnFind" runat="server" Text="Find" 106       OnClick="btnFind_Click" ValidationGroup="address" 107           OnClientClick="lstProperties" />108                      109  110          <asp:ListBox ID="lstProperties" runat="server" AutoPostBack="True" 111                   OnSelectedIndexChanged="lstProperties_SelectedIndexChanged" Visible="False" 112                                  Width="200px"></asp:ListBox>113                          114                              <asp:TextBox ID="txtOrg" runat="server" OnTextChanged="txtOrg_TextChanged" 115                                  ReadOnly="True" ValidationGroup="address2" Visible="False"></asp:TextBox>116                          117                              <asp:TextBox ID="txtLine1" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>118                          119                              <asp:TextBox ID="txtLine2" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>120                          121                              <asp:TextBox ID="txtLine3" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>122                          123                              <asp:TextBox ID="txtTown" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>124                          125                              <asp:TextBox ID="txtPostcode" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>126                          127                              <asp:Label ID="lblAddress" runat="server" CssClass="style9"></asp:Label>128                                          129                              <asp:Button ID="submitaddress" runat="server" Text="Add Details" 130                                  style="text-align: centre" CommandName="Submit" 131                                  ValidationGroup="address" PostBackUrl="~/MemberPages/account.aspx" />132  133  </asp:Content>
 Will this code work? if not can you explain why not and offer an example that will work. In the mean time I am reading up on these insert statements.
 
Regards
Mal

View 5 Replies View Related

Insert Country Code Into Columns

Nov 9, 2011

I am having a users table which contains "Mobile" column as well. I want a query to set the country code value by default into the column name so that the column should be updated with the mobile number along with the default country code.

View 10 Replies View Related

Optimization Of Unpivot / Insert Code

Sep 11, 2015

Trying to optimise the below query, I believe it's do with the estimated rows on the unpivot using Supratimes this seems to be the only sticking point.The query below is an example replicating what I'm trying to do in live, it takes around 2 seconds to run on my pc.

Create --drop --alter
Table #Actuals
(
Period1 FLOAT
, Period2 FLOAT
, Period3 FLOAT
, Period4 FLOAT

[code]....

View 8 Replies View Related

UPDATE INSERT Code Efficiency

Sep 17, 2005

Not sure what happened to my post, it seems to have disappeared. Here we go again. I have a stored procedure that I would like some feedback on, as I feel it may be inefficient as coded:

@ZUserID varchar(10)
AS
SET NOCOUNT ON

DECLARE @counter int
SET @counter = 0
WHILE @counter < 10
BEGIN
SET @counter = @counter + 1
IF EXISTS(SELECT * FROM tblWork WHERE UserID = @ZUserID And LineNumber = @counter)
BEGIN
UPDATE tblWork SET
TransID = Null,
TransCd = Null,
InvoiceNo = Null,
DatePaid = Null,
Adjustment = Null,
Vendor = Null,
USExchRate = Null
WHERE
UserID = @ZUserID And LineNumber = @counter
END
ELSE
INSERT INTO tblWork
(LineNumber,TransCd,UserID)
VALUES
(@counter,'P',@ZUserID)
END

View 2 Replies View Related

Insert HTMl Code In Database

Feb 23, 2008

Hello,

I am creating an ASP.NET web site which inserts data in a SQL database using LINQ.

One table column will hold HTML code. I am using a simple TextBox to input the data.

I would like to create my text in my computer and then copy/paste the HTML code to my TextBox and insert in the database.

What software should I use to create my text? Microsoft Office 2007, ... ? Any suggestion would be great.

Can I do it this way?

Thanks,

Miguel

View 9 Replies View Related

Retreive Html Code From Xmlfile, Insert Into Table

Nov 15, 2007

I use the following query to shred an xml and insert it into a table, but I want to have the whole html structure into the column to be able to present the formatted text in Cognos 8 BI.

WITH xmlnamespaces('http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-01-15T13:29:33' AS my)
INSERT INTO TMP_ATGFORSLAG (AtgForslagDesc)
SELECT
AtgForslagRad.value('(/my:AtgForslagRad/my:AtgForslagDesc)[1]', 'varchar(2000)') AS AtgForslagDesc
FROM dbo.DeklAtgForslagXml

The structure of the source in the xmlfile I want to import is:
<my:AtgForslagDesc>
<html xmlns="http://www.w3.org/1999/xhtml">
<ol>
<li>Text1...</li>
<li>Text2...</li>
<li>Text3...</li>
</ol>
</html>
</my:AtgForslagDesc>

How do I shred not only the text but the whole starting <html> to finishing </html> and insert it into a table I would be very happy.

View 1 Replies View Related

Not Able To Insert Text Into The Database ( Text Contains Code Snippets )

Jun 27, 2005

I have a SQL SERVER database which has Articles Table. This table
contains "Description" field which is of type "text". I am trying to
insert 800- 1000 words of data into this field. This data also contains
code snippets. I dont know for some reason it only inserts one or two
lines and thats it. No error is being thrown. I am using multiline
textbox to enter the data into the database. any ideas

It displays something like this:

test 1

By AzamSharp

Creating XML Men   // This is very long text. Actually its the whole article but it only displays three words

any ideas !

Thanks,

View 6 Replies View Related

Insert Images In SQL 2005 Express DB, Using C# Code For Asp.net 2.0 (VS 2005)

Aug 31, 2006

Help!

I found about a dozen samples and articles in the net about inserting images in a sql database, but they were either using VB, or asp only or SQL 2000 and although I tried them all, none worked...
Can you help me by posting some code on how to insert images in SQL 2005, using C# in Visual Studio 2005 (asp.net 2.0)

Thanks.

View 11 Replies View Related

How To Show Description In Report Instead Of Code (Desc For Code Is In Master Table)

Mar 28, 2007

Dear Friends,



I am having 2 Tables.

Table 1: AddressBook
Fields --> User Name, Address, CountryCode



Table 2: Country
Fields --> Country Code, Country Name


Step 1 : I have created a Cube with these two tables using SSAS.



Step 2 : I have created a report in SSRS showing Address list.

The Column in the report are User Name, Address, Country Name



But I have no idea, how to convert this Country Code to Country name.

I am generating the report using the Layout tab. ( Data | Layout | Preview ) Report1.rdl [Design]



Anyone help me to solve this issue. Because, in our project most of the transaction tables have Code and Code description in master table. I need to convert all code into corresponding description in all my reports.




Thanks in advance.





Regards
Ramakrishnan
Singapore
28 March 2007

View 4 Replies View Related

Many Lines Of Code In Stored Procedure && Code Behind

Feb 24, 2008

Hello,
I'm using ASP.Net to update a table which include a lot of fields may be around 30 fields, I used stored procedure to update these fields. Unfortunatily I had to use a FormView to handle some TextBoxes and RadioButtonLists which are about 30 web controls.
I 've built and tested my stored procedure, and it worked successfully thru the SQL Builder.The problem I faced that I have to define the variable in the stored procedure and define it again the code behind againALTER PROCEDURE dbo.UpdateItems
(
@eName nvarchar, @ePRN nvarchar, @cID nvarchar, @eCC nvarchar,@sDate nvarchar,@eLOC nvarchar, @eTEL nvarchar, @ePhone nvarchar,
@eMobile nvarchar, @q1 bit, @inMDDmn nvarchar, @inMDDyr nvarchar, @inMDDRetIns nvarchar,
@outMDDmn nvarchar, @outMDDyr nvarchar, @outMDDRetIns nvarchar, @insNo nvarchar,@q2 bit, @qper2 nvarchar, @qplc2 nvarchar, @q3 bit, @qper3 nvarchar, @qplc3 nvarchar,
@q4 bit, @qper4 nvarchar, @pic1 nvarchar, @pic2 nvarchar, @pic3 nvarchar, @esigdt nvarchar, @CCHName nvarchar, @CCHTitle nvarchar, @CCHsigdt nvarchar, @username nvarchar,
@levent nvarchar, @eventdate nvarchar, @eventtime nvarchar
)
AS
UPDATE iTrnsSET eName = @eName, cID = @cID, eCC = @eCC, sDate = @sDate, eLOC = @eLOC, eTel = @eTEL, ePhone = @ePhone, eMobile = @eMobile,
q1 = @q1, inMDDmn = @inMDDmn, inMDDyr = @inMDDyr, inMDDRetIns = @inMDDRetIns, outMDDmn = @outMDDmn,
outMDDyr = @outMDDyr, outMDDRetIns = @outMDDRetIns, insNo = @insNo, q2 = @q2, qper2 = @qper2, qplc2 = @qplc2, q3 = @q3, qper3 = @qper3,
qplc3 = @qplc3, q4 = @q4, qper4 = @qper4, pic1 = @pic1, pic2 = @pic2, pic3 = @pic3, esigdt = @esigdt, CCHName = @CCHName,
CCHTitle = @CCHTitle, CCHsigdt = @CCHsigdt, username = @username, levent = @levent, eventdate = @eventdate, eventtime = @eventtime
WHERE (ePRN = @ePRN)
and the code behind which i have to write will be something like thiscmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@eName", ((TextBox)FormView1.FindControl("TextBox1")).Text);cmd.Parameters.AddWithValue("@ePRN", ((TextBox)FormView1.FindControl("TextBox2")).Text);
cmd.Parameters.AddWithValue("@cID", ((TextBox)FormView1.FindControl("TextBox3")).Text);cmd.Parameters.AddWithValue("@eCC", ((TextBox)FormView1.FindControl("TextBox4")).Text);
((TextBox)FormView1.FindControl("TextBox7")).Text = ((TextBox)FormView1.FindControl("TextBox7")).Text + ((TextBox)FormView1.FindControl("TextBox6")).Text + ((TextBox)FormView1.FindControl("TextBox5")).Text;cmd.Parameters.AddWithValue("@sDate", ((TextBox)FormView1.FindControl("TextBox7")).Text);
cmd.Parameters.AddWithValue("@eLOC", ((TextBox)FormView1.FindControl("TextBox8")).Text);cmd.Parameters.AddWithValue("@eTel", ((TextBox)FormView1.FindControl("TextBox9")).Text);
cmd.Parameters.AddWithValue("@ePhone", ((TextBox)FormView1.FindControl("TextBox10")).Text);
cmd.Parameters.AddWithValue("@eMobile", ((TextBox)FormView1.FindControl("TextBox11")).Text);
So is there any way to do it better than this way ??
Thank you

View 2 Replies View Related

Custom Code (Embedded Code) Question

Oct 16, 2007



Hi all,

Could someone tell me if custom code function can capture the event caused by a user? For example, onclick event on the rendered report?

Also, can custom code function alter the parameters of the report, or refresh the report?

Thanks.

View 2 Replies View Related

SQL Server 2000 To SQL Server 2005 - Any Changes Required To Existing Code, System.Data.SqlClient.SqlConnection?

Dec 13, 2007

My web project (ASP.NET 2.0 / C#) runs against sql server 2000 and uses the System.Data.SqlClient.using System.Data.SqlClient;
 I use System.Data.SqlClient.SqlConnection and System.Data.SqlClient.SqlCommand to make the connections to the database and do selects and updates.  Is it correct to continue to use these against SQL Server 2005?  I ask because I made a connection string (outside of .Net) for SqlServer 2005 using the SQL native provider and it had the following - Provider=SQLNCLI.1 and any connection strings I had made (also outside of ASP.NET) fro SQL Server all used Provider=SQLOLEDB.1.  This is why I wondered if there is a different SqlClient in .Net 2.0 for SQL Server 2005?
Cheers
Al

View 1 Replies View Related

SQL Server Express Code On MSDE/SQL Server 2000

Jun 21, 2005

hi - I am developing locally using .Net 2.0/Access but just recently started trying out SQL Server Express. I have deployed my application to a host who provides 2.0 but as would be expected only MSDE/SQL server 2000. Now if I'd switch completely to SSE, would my SQL queries (which are pretty simple) work on MSDE or SQL server 2000? The only thing I see as more sophisticated sql queries would be the built-in 2.0 Roles/Membership functions... Do you think they would run smoothly on MSDE/SQL 2000?Finally... since the database is already done locally, is there any way (a stored procedure for example) to copy it's scheme if I'd create a new DB on my host's SQL server?

View 2 Replies View Related

SQL Server Code

Mar 27, 2007



string strSQL = "INSERT INTO Members (Username, Password, Email) values ('lol', 'lol', 'lol')";

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("app_data/members.mdb")); System.Data.OleDb.OleDbCommand com = new System.Data.OleDb.OleDbCommand(strSQL, conn);

conn.Open();

com.ExecuteNonQuery();

conn.Close();





The problem here is that it complains about the: "INSERT INTO Members (Username, Password, Email) values ('lol', 'lol', 'lol')";



When i use the same query at microsoft access to the same database it works fine but not in visual web developer (language: C#).



I have no idea what's the problem here, please help me!

View 1 Replies View Related

Putting SqlDataSource Code In Code-behind

Jan 25, 2007

Hi,I need some help here. I have a SELECT sql statement that will query the table. How do I get the return value from the sql statement to be assigned to a label. Any article talk about this? Thanks  geniuses.  

View 2 Replies View Related

Can't Connect To Db Via Code, But Can From SQL Server.

Apr 10, 2004

Having an issue where I can connect to a remote SQL Database server via enterprise manager, however using the exact same db credentials, I can't connect via the .NET SqlConnection object...

Anyone have this error? Did you ever figure it out?

The error I get is: "SQL Server does not exist or access denied."

Again... I'm using the EXACT same user name, password, port number. I've setup an alias in Client Network Utility....

The SQL Server Enterprise is running on the exact same PC as the code I'm trying to execute.



Thanks for any help!

View 2 Replies View Related

Connect To SQL Server Code

Feb 26, 2006

Hello,
I am new to ASP.net. I just installed MS Sql Server and Visual Web Developer 2005 Express Edition.
Can any help with the code to connect to SQL server?

Thank you

View 1 Replies View Related

SQL Server CODE Pages

Jul 6, 1999

Does anyone know a workaround for the code page translation that occurs if you use bcp to
transfer data in and out of SQL Server. I have a table that I am losing certain characters in the
transfers.

SQL Server 7.0 has the -C code page specifier added to BCP to address this but I am running 6.5 currently.

Any ideas on how to deal with this?

Thanks,
Phil

View 1 Replies View Related

Can I Use C# Code In SQL Server Reports

Apr 17, 2008

Hello All,

I have created a SQL Server Report using VS2005.
Now I want to write my own code for an auto calculated field.

When I explored the Visual Studio , I found that I can write code in
"Report >> Report Properties" but the code can only be written in VB.NET

It is amazing for me because i want to write my code in C#.

Can any one help that how can i write C# methods in Code Area of "Report >> Report Properties"?
OR IS IT IMPOSIBLE TO WRITE CODE IN C#


I will be waiting for your kind reply.

Regards

View 1 Replies View Related

SQL Server 2008 :: Insert Data Into Table Variable But Need To Insert 1 Or 2 Rows Depending On Data

Feb 26, 2015

I am writing a query to return some production data. Basically i need to insert either 1 or 2 rows into a Table variable based on a decision as to does the production part make 1 or 2 items ( The Raw data does not allow for this it comes from a look up in my database)

I can retrieve all the source data i need easily but when i come to insert it into the table variable i need to insert 1 record if its a single part or 2 records if its a twin part. I know could use a cursor but im sure there has to be an easier way !

Below is the code i have at the moment

declare @startdate as datetime
declare @enddate as datetime
declare @Line as Integer
DECLARE @count INT

set @startdate = '2015-01-01'
set @enddate = '2015-01-31'

[Code] .....

View 1 Replies View Related

Can Anyone Tell Me Why This Code Won't Update My SQL Server Database?

Mar 12, 2005

I am trying to perform a simple update to a SQL Server database table and I can't figure out why this simple UPDATE command doesn't work. I am performing the same thing in another page for owner information and it works just fine. It seems that some of my code won't work even though the syntax is correct and there is no reason for it not to work.

I have hardcoded text for some of the fields and the UPDATE code below works but when I try to use the information that may be in the Textbox, the code won't do the UPDATE. Please help me figure out what is going on.

Thanks



Sub btnUpdate_Click_1(sender As Object, e As EventArgs)
Dim UserCode as String
Dim PropertyCode as String
Dim UnitCode as String
Dim address1 as String
Dim address2 as String
Dim address3 as String
Dim city as String
Dim zip_Code as String
Dim description as String
Dim price_Range as String
Dim state as String
Dim type_Property as String
Dim property_Status as String

if chkChangeState.Checked = True then
state = ddl_State.SelectedItem.Value
else
state = lblState.Text
end if

if chkPropertyType.Checked = True then
type_Property = ddlPropertyType.SelectedItem.Value
else
type_Property = lblPropertyType.Text
end if

if chkPropertyStatus.Checked = True then
property_Status = ddlPropertyStatus.SelectedItem.Value
else
property_Status = lblPropertyStatus.Text
end if

txtPropertyCode.ReadOnly = False
txtUnitCode.ReadOnly = False

'address1 = txtAddress1.Text
'address2 = txtAddress2.Text
'address3 = txtAddress3.Text
'city = txtCity.Text
'zip_Code = txtZipCode.Text
'description = txtDescription.Text
'price_Range = txtPriceRange.Text

UserCode = Server.HtmlEncode(Request.Cookies("UCodeCookie")("Code"))
PropertyCode = txtPropertyCode.Text
UnitCode = txtUnitCode.Text

Dim connectionString As String = "server='(local)'; trusted_connection=true; database='master'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "UPDATE [Property_db] SET [Address1]=@Address1, [Address2]=@Address2, [Address3]=@Address3, [City]=@City, [State]=@State, [Zip_Code]=@Zip_Code, [Type_Property]=@Type_Property, [Description]=@Description, [Property_Status]=@Property_Status, [Price_Range]=@Price_Range WHERE ([Property_db].[Code] = @Code) AND ([Property_db].[Prop_Code] = @Prop_Code) AND ([Property_db].[Unit_Code] = @Unit_Code)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_code As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_code.ParameterName = "@Code"
dbParam_code.Value = UserCode
dbParam_code.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_code)
Dim dbParam_prop_Code As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_prop_Code.ParameterName = "@Prop_Code"
dbParam_prop_Code.Value = PropertyCode
dbParam_prop_Code.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_prop_Code)
Dim dbParam_unit_Code As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_unit_Code.ParameterName = "@Unit_Code"
dbParam_unit_Code.Value = UnitCode
dbParam_unit_Code.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_unit_Code)
Dim dbParam_address1 As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_address1.ParameterName = "@Address1"
dbParam_address1.Value = txtAddress1.Text
dbParam_address1.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_address1)
Dim dbParam_address2 As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_address2.ParameterName = "@Address2"
dbParam_address2.Value = txtAddress2.Text
dbParam_address2.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_address2)
Dim dbParam_address3 As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_address3.ParameterName = "@Address3"
dbParam_address3.Value = txtAddress3.Text
dbParam_address3.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_address3)
Dim dbParam_city As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_city.ParameterName = "@City"
dbParam_city.Value = txtCity.Text
dbParam_city.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_city)
Dim dbParam_state As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_state.ParameterName = "@State"
dbParam_state.Value = state
dbParam_state.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_state)
Dim dbParam_zip_Code As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_zip_Code.ParameterName = "@Zip_Code"
dbParam_zip_Code.Value = txtZipCode.Text
dbParam_zip_Code.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_zip_Code)
Dim dbParam_type_Property As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_type_Property.ParameterName = "@Type_Property"
dbParam_type_Property.Value = type_Property
dbParam_type_Property.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_type_Property)
Dim dbParam_description As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_description.ParameterName = "@Description"
dbParam_description.Value = txtDescription.Text
dbParam_description.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_description)
Dim dbParam_property_Status As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_property_Status.ParameterName = "@Property_Status"
dbParam_property_Status.Value = property_Status
dbParam_property_Status.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_property_Status)
Dim dbParam_price_Range As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_price_Range.ParameterName = "@Price_Range"
dbParam_price_Range.Value = txtPriceRange.Text
dbParam_price_Range.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_price_Range)

Dim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close
End Try

'if Not rowsAffected then
Response.Redirect("./editproperty.aspx")
'end if
End Sub

View 1 Replies View Related

Debugging SQL Server Statements In Code

Jul 28, 2005

How can I view the raw SQL code that ASP.NET sends to SQL Server when using parameters?

The code below doesn't display the actual SQL statement, but instead: System.Data.SqlClient.SqlCommand.

string SQL = "INSERT INTO [BLAH] VALUES (@startDate)";
SqlConnection mySqlConn = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
SqlCommand mySqlCmd = new SqlCommand(SQL, mySqlConn);

mySqlCmd.Parameters.Add(new SqlParameter("@startDate", SqlDbType.DateTime));
mySqlCmd.Parameters["@startDate"].Value = Request.Form["start_date"];

lblSQLDebug.Text = mySqlCmd.ToString();

TIA.

View 6 Replies View Related

SQL Server 7 Error Code : 73301

Sep 28, 1999

Hi,

Do anyone know what's the error for code 73301?

Is there anyway for me to trace source of the error no?

The error msg is as below:
NSQL 73301: EXcProd does not exist (nsp_Archive_Table)

EXcProd is the database, where nsp_Archive_Table is the store procedure.
Actually, nsp_Archive_Table do exist in the database but the system keep saying that it's not.

Thanks

View 2 Replies View Related

Free SQL Code Beautifier For SQL Server

Jan 7, 2005

Hello,
maybe you are interested in this.
I wrote a java applet on www.sqlinform.com which is a SQL Code beautifier / formatter. It is for all kind of SQL (DB2, ORACLE; Access, Informix, etc). The only thing you need is a Java Runtime Environment (which should be available in most cases). You can beautify SQL statements out of program code and format them for Java, ASP, VB, PHP.
Regards
GuidoMarcel

View 4 Replies View Related

SQl 2005 Server Not Accesible Through ASP.Net 1.1 Code

Aug 31, 2006

I am trying to connect a production SQL Server 2005 which is under firewall through an Application written in ASP.Net 1.1 and I get error "SQL Server not available or Access Denied".

I am able to connect to the Server through SQL Mgr also using the same Code and Web.Config file I am able to Connect to the SErver using ASP.Net 2.0.

I am able to run the application for a SQL Server 05 which is in the same domain as of the Application Server.

My Application is not working only when I use ASP.Net 1.1 code for the Remote SQL Server 05 which is under Firewall. But for the same Server ASP.Net 2.0 works fine.

I have searched a lot for the problem and port No, DBNETLIB update is also tried.

Please let me know if anyone has came across such problem or knows the possible cause of the problem.

Sunil.

View 8 Replies View Related

Sql Server Custom Code Issue

Sep 12, 2007

I created a report in SQL Server 2005 using SQL Server 2005. I added a custom code to the report as:

function getpiececount_parent(byval qb_prodcode as string,byval s_date as string,byval e_date as string)

dim conn as new System.Data.SqlClient.SqlConnection

conn.ConnectionString= "Data Source=xxxx;Initial Catalog=xxxx;User Id=xxxx;Password=xxxxx "

conn.open()

dim sql as string

sql="select query using parameters"

dim cmd as new System.Data.SqlClient.SqlCommand

cmd.connection=conn

cmd.commandtext=sql

cmd.Parameters.AddWithValue("@stDate",s_date)

cmd.Parameters.AddWithValue("@edDate",e_date)

cmd.Parameters.AddWithValue("@qbprodcode",qb_prodcode)



dim retval =cmd.ExecuteScalar()

if retval is system.dbnull.value then

retval=0

end if



cmd.dispose()

conn.close()

return retval

end function



For the above function I added reference to the System.Data . The report works as desired when I execute in the VS 2005 IDE but when I deploy the report on the reporting server and execute it from there the function doesn€™t execute and returns me #Error.

Can any one provide some insight into it to as to how i can resolve this issue.

View 5 Replies View Related

How Do You Code The Dropping Of A Linked Server Def?

Nov 8, 2007



There are procs to add linked servers, and procs to add and delete linkedserver logins, but I dont see a proc to delete the actual linked server definition. And yet EM will drop the definition of a linked server. So the obvious question is "How do you code the dropping of a linked server?

Thanks!

Michael

View 4 Replies View Related

How To Code DateTime-Literal In SQL Server

Apr 20, 2006

Hi,

I'm a newbee to SQL Server. I have a very simple question to you experts: How should I code a literal of the "datetime"-Datatype? For Example in the VALUES-clause of an SQL-statement. I have tested several "formats" ('20.04.2006 11:15:00' with an 4-digit year enclosed in single apostrophes) but all i earned is an exception!

Any help very appreciated!

Thanks in advance and best regards

Reiner

PS.: I'm using a german-localized database (thus the date-format dd.MM.yyyy).



View 9 Replies View Related

SQL Server 2005 Code Error

Aug 18, 2006

Hey,

I need someone to look at a small piece of code and tell me where I'm going wrong in SQL 2005 Server. Where should I post?

Thanks in advance,

Danny

Problem: When I run this I'm told NoOfContractsCount is an invalid column name when I try creating my cusor

USE SLXDEV

SELECT Count(MCS2_CONTRACT.accountid) AS NoOfContractsCOUNT, MCS2_CONTRACT.accountid, CONTACTID

INTO #TempTable

FROM sysdba.MCS2_CONTRACT, CONTACT

WHERE MCS2_CONTRACT.accountid = CONTACT.accountid

GROUP BY MCS2_CONTRACT.accountid, CONTACTID

HAVING Count(MCS2_CONTRACT.accountid) > 1

DECLARE @CountTemp int

DECLARE @accountIDTemp CHAR(12)

DECLARE @ContactIDTemp CHAR(12)

DECLARE @AccountName VARCHAR(128)

DECLARE @LastName VARCHAR(32)

DECLARE @FirstName VARCHAR(32)

DECLARE @WorkPhone VARCHAR(32)

DECLARE @Fax VARCHAR(32)

DECLARE @Mobile VARCHAR(32)

DECLARE @Email VARCHAR(128)

DECLARE @Title VARCHAR(64)

DECLARE @UserField1 VARCHAR(80)

DECLARE @UserField2 VARCHAR(80)

DECLARE @UserField3 VARCHAR(80)

DECLARE searchCursor CURSOR

FOR

SELECT NoOfContractsCOUNT, accountid, ContactID

FROM #TempTable

OPEN searchCursor

FETCH NEXT FROM searchCursor INTO @CountTemp, @accountIDTemp, @ContactIDTemp

While (@@FETCH_STATUS <> -1)

BEGIN

IF (@@FETCH_STATUS <> -2)

BEGIN

PRINT 'GOT HERE'

SELECT @accountIDTemp = AccountID, -- SELECT DISTINCT?

@AccountName = Account, @LastName = LASTNAME, @FirstName = FIRSTNAME,

@WorkPhone = WORKPHONE, @Fax = FAX, @Mobile = MOBILE, @Email = EMAIL,

@Title = TITLE, @UserField1 = USERFIELD1, @UserField2 = USERFIELD2,

@UserField3 = USERFIELD3

FROM CONTACT

WHERE AccountID = @AccountIDTemp

declare @counter int

set @counter = 1

while @counter < @CountTemp

begin

INSERT INTO CONTACT(CONTACTID, ACCOUNTID, ACCOUNT,

FIRSTNAME, LASTNAME, WORKPHONE, FAX, MOBILE, EMAIL,

TITLE, USERFIELD1, USERFIELD2, USERFIELD3)

VALUES

(@ContactIDTemp, @accountIDTemp, @AccountName, @FirstName,

@LastName, @WorkPhone, @Fax, @Mobile, @Email, @Title,

@UserField1, @UserField2, @UserField3)

set @counter = @counter + 1

end

END

END

DROP TABLE #TempTable

View 6 Replies View Related







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