End If

advertisement
1|Page
Table of Content
Contents
Method for creation of Function .................................................................................................................. 2
Method for creation of Stored Procedure .................................................................................................... 2
Method for Creation of If Statement in SQL ................................................................................................. 2
Code to Call function from SQL Server ......................................................................................................... 3
Code to Call Stored Procedure from SQL Server........................................................................................... 3
Code to populate Grid view .......................................................................................................................... 4
Code to Use direct cast to use find control for page having Master page ................................................... 4
Code on how to Use Collection ..................................................................................................................... 4
Code to Send an E-Mail ................................................................................................................................. 6
Color Grid View Row Based on Cell Value .................................................................................................... 7
Color Grid View Cell Based on Cell Value...................................................................................................... 7
Method to Create Consequative number in Grid ......................................................................................... 8
Method to Populate Grid Data Source Using SQL Parameter and Having Parameter ................................. 8
Method to show the Data Source for the Grid ............................................................................................. 9
Mathod to Set Security on a Page................................................................................................................. 9
Function in SQL which Checks IS Allowed ................................................................................................... 10
Adjusting Connection String On The fly ...................................................................................................... 10
How too access master page control from Child page ............................................................................... 12
Function to Translate a Language after creating table on SQL Server ....................................................... 12
SQL Query Function for translation Page.................................................................................................... 13
How to Excute a Function in sql Editor ....................................................................................................... 14
How to declare Table returning SQL Function ............................................................................................ 15
How to load table returning SQL Function in using visual Basic ................................................................. 16
SQL Function to insert data in to Table....................................................................................................... 16
SQL Function which add data to a table and returns value this is good for file Naming getting id of last
added record ............................................................................................................................................... 17
How to call and receive SQL Function table with returning value .............................................................. 20
Best technique when retrieving document for Editing from SQL ............................................................... 26
2|Page
Method for creation of Function
USE [CSD]
GO
/****** Object: UserDefinedFunction [dbo].[TimeId]
Script Date:
11/28/2011 15:15:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
Alter function [dbo].[SumLanT] (@lang int) returns int
as
Begin
declare @Ans as int
select @Ans = sum([Page]) from Sub_View_ByNameFinal where Lang_Id = @lang
return @Ans
End
Method for creation of Stored Procedure
USE [CSD]
GO
/****** Object: StoredProcedure [dbo].[UpdateIntRoomT]
Script Date:
11/30/2011 08:52:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[UpdateIntRoomT] (@STT Varchar(5), @ETT Varchar(5),
@STID int, @ETID int, @dur decimal(18,2), @id int, @RIDD int)
As
Begin
Update Int_Busy set Start_Time = @STT, End_Time = @ETT, Start_Time_Id = @STID
, End_Time_Id = @ETID, Int_Hour = @dur where IDMR= @id and RRID = @RIDD
Update Room_Busy set Start_Time = @STT, End_Time = @ETT, Start_Time_Id =
@STID , End_Time_Id = @ETID, Duration = @dur where IDMR= @id and RRID = @RIDD
End
Method for Creation of If Statement in SQL
USE [CSD]
GO
/****** Object: UserDefinedFunction [dbo].[bool2]
08:43:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Script Date: 11/30/2011
3|Page
ALTER function [dbo].[bool2] (@num int) returns bit
as
Begin
declare @Ans as bit
if (@num >= 0)
set @Ans = 'True'
else
set @Ans = 'False'
return @Ans
End
Code to Call function from SQL Server
Try
Dim com2 As New SqlCommand()
con.Open()
com2.Connection = con
com2.CommandText = "select dbo.SumLan(@Lan)"
com2.CommandType = CommandType.Text
com2.Parameters.Add("@Lan", Data.SqlDbType.Char)
com2.Parameters("@Lan").Value = "Arabic"
lblArPage.Text = FormatNumber(com2.ExecuteScalar(), ,
TriState.True)
con.Close()
Catch ex As Exception
Response.Write(ex.ToString)
Finally
con.Close()
end Try
Code to Call Stored Procedure from SQL Server
Try
con.Open()
com.Connection = con
com.CommandText = "UpdateIntRoomT"
com.CommandType = CommandType.StoredProcedure
com.Parameters.Add("@STT", Data.SqlDbType.VarChar)
com.Parameters("@STT").Value = ddSTA.SelectedValue
com.Parameters.Add("@ETT", Data.SqlDbType.VarChar)
com.Parameters("@ETT").Value = ddENA.SelectedValue
com.Parameters.Add("@STID", Data.SqlDbType.Int)
com.Parameters("@STID").Value = CInt(lblStID.Text)
com.Parameters.Add("@ETID", Data.SqlDbType.Int)
com.Parameters("@ETID").Value = CInt(lblEnId.Text)
com.Parameters.Add("@dur", Data.SqlDbType.Decimal)
com.Parameters("@dur").Value = CDec(lbldura.Text)
com.Parameters.Add("@Id", Data.SqlDbType.Int)
com.Parameters("@ID").Value = ddTACode.SelectedValue
4|Page
com.Parameters.Add("@RIDD", Data.SqlDbType.Int)
com.Parameters("@RIDD").Value = CInt(lblRRIDT.Text)
com.ExecuteNonQuery()
GVRoomT.DataBind()
con.Close()
Catch ex As Exception
Response.Write(ex.ToString)
End Try
Code to populate Grid view
con.Open()
Dim daa As New SqlDataAdapter(cmd3)
Dim dsa As New DataSet()
daa.Fill(dsa, "Translate")
GVMeetingRequest.DataSource = dsa.Tables(0)
'the grid is populated as per the retrived dataset
GVMeetingRequest.DataBind()
GVMeetingRequest.Visible = True
DVMeet.DataBind()
DVMeet.Visible = True
con.Close()
Code to Use direct cast to use find control for page having Master page
Public Sub resetIntM()
Dim contp As ContentPlaceHolder =
TryCast(Page.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)
Dim LBMT As Label
Dim IDLBMT As String
For i = 1 To 25
IDLBMT = "LBMT" & i
LBMT = DirectCast(contp.FindControl(IDLBMT), Label)
LBMT.BackColor = Drawing.Color.White
LBMT.ForeColor = Drawing.Color.White
Next
End SubCode for
Code on how to Use Collection
Protected Sub btnApproval_Click(ByVal sender As Object, ByVal e As
System.EventArgs)
'This Variable is declared to collect the array of id's of row
sellected
Dim coll As New StringCollection()
Dim strid As String = String.Empty
'this for loop checks all the available rows if it is checked or not
and if checked
5|Page
'it will add the id numbers in the collection variable
For i As Integer = 0 To gvDatas.Rows.Count - 1
Dim CheckSel As CheckBox =
DirectCast(gvDatas.Rows(i).Cells(0).FindControl("CheckSelect"), CheckBox)
If CheckSel IsNot Nothing Then
If CheckSel.Checked Then
strid = gvDatas.Rows(i).Cells(1).Text
coll.Add(strid)
End If
End If
Next
'Calls the function called updatevalues
UpdateValues(coll)
gvDatas.DataBind()
End Sub
Private Sub UpdateValues(ByRef coll As StringCollection)
'This sub recives a string collections as a parameter
Dim con As New SqlConnection(strConn)
Dim cmd As New SqlCommand()
Dim IDs As String
'This builds the string list which was selected and paseed as a
parameter as a string
'collection separated by comma so that the sql command choose among
If coll.Count = 0 Then
Else
For Each id As String In coll
IDs += id.ToString() & ","
Next
Try
' The update string is constructed so that it will update the
database if the
' number is available in the collection
Dim strIds As String = IDs.Substring(0, IDs.LastIndexOf(","))
' The update string is constructed so that it will update the
database if the
' number is available in the collection
'This Update query updates the Work Flow Tags to for approval
those sent to the director
Dim strUpd As String = "Update Translate set flow = 'For
Approval' where number in (" + strIds + ")"
cmd.CommandType = CommandType.Text
cmd.CommandText = strUpd
cmd.Connection = con
con.Open()
'update query is excuted and the fields would be updated
cmd.ExecuteNonQuery()
Catch ex As SqlException
Dim errorMsg As String = "Error in Updating"
errorMsg = errorMsg + ex.Message
6|Page
Throw New Exception(errorMsg)
Finally
con.Close()
End Try
End If
End Sub
Code to Send an E-Mail
Private Sub SendEmail(ByRef TID As String, ByRef NUMS As String, ByRef id As
Integer)
Dim join2 As String =
WebConfigurationManager.ConnectionStrings("DB").ConnectionString
Dim con As New SqlConnection(join2)
'Dim int As String
Dim tcid As String = TID
Dim sqlE, sender1, Title, sqlT As String
sqlE = "Select Outlook from Reviser where Rev_Id = " & tcid
SqlT = "Select [Title of the Document] from translate where number =
" & id
sender1 = AssignTo(sqlE)
Title = Titleof(sqlT)
'#Region "send message to end user"
Dim msgToenduser As New MailMessage()
msgToenduser.IsBodyHtml = True
msgToenduser.From = New MailAddress("No-Reply-ConferenceWeb@africaunion.org")
msgToenduser.[To].Add(New MailAddress(sender1))
Dim ccc As String = "conferenceweb@africa-union.org"
msgToenduser.[CC].Add(New MailAddress(ccc))
If sender1 IsNot Nothing Then
msgToenduser.Subject = "You are Assigned to Translate a Document
Coded " & NUMS
msgToenduser.Body += "This is an automatically generated message
from ConferenceWeb. Please don't reply !<br><br>"
msgToenduser.Body += "You are Assigned to Translate a Document
Coded " & NUMS & " with title <B><i>" & Title & "</B></I> "
msgToenduser.Body += "To view Your Assignment please log in to
http://conferenceweb.africanunion.local/login.aspx and go to Translator Page
and choose your language groupe :<br> <br>"
msgToenduser.Body += "Thank You <br>"
msgToenduser.Body += "Assignment Date Time Stamp " & Now() & "
<br> <br> <br>"
msgToenduser.Body += "African Union Comission <br>"
msgToenduser.Body += "Conference Services Directorate <br>"
msgToenduser.Body += "Telephone: 251-11-551-7700 Ext. 250
<br><br>"
msgToenduser.Body += "E-Mail: Conferenceweb@africa-union.org
<br>"
msgToenduser.Body += "Website:
http://conferenceweb.africanunion.local/login.aspx <br>"
Dim smtp As New SmtpClient()
smtp.Host = ConfigurationManager.AppSettings("MailServer")
7|Page
Dim cred As New NetworkCredential("conferenceweb", "123456",
"africanunion.local")
smtp.Credentials = cred
smtp.UseDefaultCredentials = False
Try
smtp.Send(msgToenduser)
Catch ex As Exception
Response.Write("Message to The Reviser did not Succeed " &
sender1)
End Try
End If
'--------------------------Mail Test-----------------------End Sub
Color Grid View Row Based on Cell Value
Protected Sub gvDatas_RowDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvDatas.RowDataBound
'This sub is called per each row binding and colors the grid based on
Status of the documents
If e.Row.RowType = DataControlRowType.DataRow Then
Dim stat As String
'This row evaluates and puts the value in stat as per the
Finalised columon result
stat = DataBinder.Eval(e.Row.DataItem, "Finalised").ToString()
If stat = "" Then
e.Row.BackColor = System.Drawing.Color.Lime
ElseIf stat = "Not Finalised" Then
e.Row.BackColor = System.Drawing.Color.LightGreen
ElseIf stat = "Old System" Then
e.Row.BackColor = System.Drawing.Color.LightCyan
ElseIf stat = "Rejected" Then
e.Row.BackColor = System.Drawing.Color.LightPink
Else
e.Row.BackColor = System.Drawing.Color.LightSkyBlue
End If
End If
Color Grid View Cell Based on Cell Value
Protected Sub GVApproveEdit_RowDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewRowEventArgs) Handles
GVApproveEdit.RowDataBound
Dim aa, EA, FA, PA As String
If e.Row.RowType = DataControlRowType.DataRow Then
'Dim stat As String
'This row evaluates and puts the value in stat as per the
Finalised columon result
aa = DataBinder.Eval(e.Row.DataItem, "AA").ToString()
If aa = "True" Then
e.Row.Cells(5).BackColor = System.Drawing.Color.Lime
Else
End If
8|Page
EA = DataBinder.Eval(e.Row.DataItem, "EA").ToString()
If EA = "True" Then
e.Row.Cells(2).BackColor = System.Drawing.Color.Lime
Else
End If
FA = DataBinder.Eval(e.Row.DataItem, "FA").ToString()
If FA = "True" Then
e.Row.Cells(3).BackColor = System.Drawing.Color.Lime
Else
End If
PA = DataBinder.Eval(e.Row.DataItem, "PA").ToString()
If PA = "True" Then
e.Row.Cells(4).BackColor = System.Drawing.Color.Lime
Else
End If
End If
End Sub
Method to Create Consequative number in Grid
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
Method to Populate Grid Data Source Using SQL Parameter and Having
Parameter
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DB %>"
SelectCommand="SELECT [Number], [Number_Sub],
[Department], [Title], [Origional Language] AS Origional_Language, [Status],
[Soft_Copy], [Soft_Copy_Original], [Trans_ID], [Translator_Name], [TADate],
[Rev_ID], [Reviser_Name], [RADate], [Proof_ID], [ProofReader_Name], [PADate],
[Sec_ID], [Secreretary_Name], [SADate], [Finalised Date] AS Finalised_Date,
[Recived Date] AS Recived_Date, [Dead Line] AS Dead_Line, [All L Finalised]
AS All_L_Finalised, [Dead Line Gap by All Language Unit] AS
Dead_Line_Gap_by_All_Language_Unit, [Dead Line Gap by Language Unit] AS
Dead_Line_Gap_by_Language_Unit, [No of Days Given] AS No_of_Days_Given,
[Page], [Dead Line By All Language Unit] AS Dead_Line_By_All_Language_Unit,
[Dead Line By a Language Unit] AS Dead_Line_By_a_Language_Unit, [MonthT],
[Year], [Day], [Week] FROM [Sub_View_ByNameFinal] WHERE ([Number_Sub] =
@Number_Sub)">
<SelectParameters>
<asp:ControlParameter ControlID="lblCode"
Name="Number_Sub" PropertyName="Text"
9|Page
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Method to show the Data Source for the Grid
<asp:DetailsView ID="dvDoc" runat="server" AutoGenerateRows="False"
CellPadding="2" DataSourceID="SqlDataSource1"
ForeColor="#333333" GridLines="None" Height="50px"
Width="500px">
<FooterStyle BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" />
<RowStyle BackColor="#CCFF99" />
<FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" />
<PagerStyle BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
Mathod to Set Security on a Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Dim Joinn As New
SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
Dim con As New
SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
Dim command As New SqlCommand("Select Deprtment from Department",
Joinn)
Dim join2 As String =
WebConfigurationManager.ConnectionStrings("DB").ConnectionString
Dim sql2 As String
Dim res As Boolean
Try
Dim com2 As New SqlCommand()
con.Open()
com2.Connection = con
com2.CommandText = "select dbo.isallowed(@PID, @UN)"
com2.CommandType = CommandType.Text
com2.Parameters.Add("@PID", Data.SqlDbType.Int)
com2.Parameters("@PID").Value = 12
com2.Parameters.Add("@UN", Data.SqlDbType.NVarChar)
com2.Parameters("@UN").Value = Page.User.Identity.Name.ToLower()
res = com2.ExecuteScalar()
con.Close()
Catch ex As Exception
Response.Write(ex.ToString)
Finally
con.Close()
End Try
If res Then
10 | P a g e
Response.Write("welcome " & Page.User.Identity.Name.ToString)
Else
Response.Write("You Are Not Allowed to Access this Page")
Response.Redirect("~/Default.aspx?field1=1")
End If
End Sub
Function in SQL which Checks IS Allowed
USE [CSD]
GO
/****** Object: UserDefinedFunction [dbo].[isAllowed]
Script Date:
12/10/2012 10:57:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER function [dbo].[isAllowed] (@PID int, @UN varchar(50)) returns bit
as
Begin
declare @Ans as bit
declare @Resp as bit
select @Resp = Allowed from Page_View where PID = @PID and User_Namee = @UN
if (@Resp = 'True')
set @Ans = 'True'
else
set @Ans = 'False'
return @Ans
End
Adjusting Connection String On The fly
APP.Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DB" providerName="System.Data.sqlclient" connectionString="" />
</connectionStrings>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log ->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event
Log -->
11 | P a g e
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name
of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener"
initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
</configuration>
<add name="DB2" connectionString="Server=MARGA-CONF-LAP database=CSD;uid=MARGA-CONFLAP\merga" />
<add name="DB1" connectionString="Data Source=.;Initial Catalog=CSD;Integrated
Security=True"
providerName="System.Data.SqlClient" />.
Now programmatically referring and Changing the config file
VB Code
Imports
Imports
Imports
Imports
System.Data.SqlClient
System.Xml
System.Configuration
System.Text
Public Class Form1
Private Sub btnData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnData.Click
Try
'Constructing connection string from the inputs
Dim Con As New StringBuilder("Data Source=")
Con.Append(txtServer.Text)
Con.Append(";Initial Catalog=")
Con.Append(txtDatabase.Text)
Con.Append(";Integrated Security=SSPI;")
Dim strCon As String = Con.ToString()
updateConfigFile(strCon)
'Create new sql connection
Dim Db As New SqlConnection()
'to refresh connection string each time else it will use previous connection
string
ConfigurationManager.RefreshSection("connectionStrings")
Db.ConnectionString = ConfigurationManager.ConnectionStrings("DB").ToString()
'To check new connection string is working or not
Dim da As New SqlDataAdapter("select * from department", Db)
12 | P a g e
'Dim da As New SqlDataAdapter("select * from employee")
'incase earlier Visualstudios
Dim dt As New DataTable()
da.Fill(dt)
cmbTestValue.DataSource = dt
cmbTestValue.DisplayMember = "deprtment"
Catch Ex As Exception
MessageBox.Show(ConfigurationManager.ConnectionStrings("DB").ToString() &
".This is invalid connection", "Incorrect server/Database")
End Try
End Sub
Public Sub updateConfigFile(ByVal con As String)
'updating config file
Dim XmlDoc As New XmlDocument()
'Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
For Each xElement As XmlElement In XmlDoc.DocumentElement
If xElement.Name = "connectionStrings" Then
'setting the coonection string
xElement.FirstChild.Attributes(2).Value = con
End If
Next
'writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
End Sub
End Class
The form
How too access master page control from Child page
' verry Very Importany this is the way we access master page control
CType(Master.FindControl("lblMasterTitleMenu7"), HyperLink).Text = trans(7, lan)
CType(Master.FindControl("lblMenuCalendar8"), HyperLink).Text = trans(8, lan)
CType(Master.FindControl("lblMenueCalendar9"), HyperLink).Text = trans(9, lan)
CType(Master.FindControl("lblMenuCalendar10"), HyperLink).Text = trans(10, lan)
Function to Translate a Language after creating table on SQL Server
Protected Sub ddLan_SelectedIndexChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles ddLan.SelectedIndexChanged
Dim lan As Integer
lan = CInt(ddLan.SelectedValue)
lblmeetingTitle1.Text = trans(1, lan)
lblMeetingAgenda2.Text = trans(2, lan)
lblMeetingDoc3.Text = trans(3, lan)
lblMeetingSpeach4.Text = trans(4, lan)
13 | P a g e
lblMeetingInformation5.Text = trans(5, lan)
lbllang6.Text = trans(6, lan)
' verry Very Importany this is the way we access master page control
CType(Master.FindControl("lblMasterTitleMenu7"), HyperLink).Text = trans(7, lan)
CType(Master.FindControl("lblMenuCalendar8"), HyperLink).Text = trans(8, lan)
CType(Master.FindControl("lblMenueCalendar9"), HyperLink).Text = trans(9, lan)
CType(Master.FindControl("lblMenuCalendar10"), HyperLink).Text = trans(10, lan)
End Sub
Public Function trans(ByVal id As Integer, ByVal lan As Integer) As String
Dim join2 As String =
WebConfigurationManager.ConnectionStrings("DB").ConnectionString
Dim con As New SqlConnection(join2)
' Dim cmd As New SqlCommand(sql, con)
Dim sql As String
Dim cmd As New SqlCommand
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "select dbo.lblTrans (@id, @Lan)"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("@id", Data.SqlDbType.Int)
cmd.Parameters("@id").Value = id
cmd.Parameters.Add("@Lan", Data.SqlDbType.NVarChar)
cmd.Parameters("@Lan").Value = lan
trans = cmd.ExecuteScalar()
con.Close()
Catch ex As Exception
Response.Write("Error occured on making Translation on mmMeeting Page " &
ex.ToString)
Finally
con.Close()
End Try
Return trans
End Function
End Class
SQL Query Function for translation Page
-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--- This block of comments will not be included in
-- the definition of the function.
-- ================================================
use [CSD]
14 | P a g e
Go
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:
<Description, ,>
-- =============================================
CREATE FUNCTION LblTrans
(
-- Add the parameters for the function here
@id int,
@lan int
)
RETURNS varchar(500)
AS
BEGIN
-- Declare the return variable here
DECLARE @Trans as varchar(500)
if (@lan = 1)
SELECT @Trans = Arabic from mmTranslation where ID = @id
else if (@lan = 2)
SELECT @Trans = English from mmTranslation where ID = @id
else if (@lan = 3)
SELECT @Trans = French from mmTranslation where ID = @id
else
SELECT @Trans = Portuguese from mmTranslation where ID = @id
-- Return the result of the function
RETURN @Trans
END
GO
How to Excute a Function in sql Editor
declare @ans as nvarchar(500)
exec @ans= lbltrans 1,3
print @ans
15 | P a g e
How to declare Table returning SQL Function
USE [BestSuk]
GO
/****** Object: UserDefinedFunction [dbo].[CardBought]
11/29/2015 09:12:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Script Date:
ALTER FUNCTION [dbo].[CardBought](@UseName Nvarchar(50))
RETURNS @CB TABLE
(
-- Columns returned by the function
[Full Name] nvarchar(50) NULL,
[Purchased Date] Datetime NULL,
[Card Serial] nvarchar(22) NULL,
[Card Number] nvarchar(28) NULL,
[Card Amount] numeric (18,0) NULL,
[Serial] numeric (18,0) NULL,
[Purchase Mode] nvarchar (50) NULL
)
AS
-- Returns the first name, last name, job title, and contact type for the
specified contact.
BEGIN
DECLARE
@Pdate Date,
@Cserial nvarchar(22),
@Cnumber nvarchar(28),
@CAmount numeric(18,0),
@FName nvarchar(50),
@Serial numeric(18,0),
@PurMode nvarchar(50)
-- Get common contact information
declare @UIDD as uniqueidentifier;
select @UIDD = UserID FROM aspnet_Users where UserName =@UseName;
insert into @CB([Full Name] ,[Purchased Date] ,[Card Serial] ,[Card Number],
[Card Amount],
[Serial],[Purchase Mode])
SELECT
FullName,
[Date],
T.ser,
T.num,
T.Amount,
T.Serial,
T.Purchase_mode
FROM CardTransaction T, UserMore U
where T.UserID= @UIDD and U.UserDetID = @UIDD
order by T.TID desc ;
RETURN;
16 | P a g e
END;
How to load table returning SQL Function in using visual Basic
Private Sub loadGrid()
Dim con As SqlConnection ' Connection Variable
Dim com As SqlCommand
Dim dt As DataTable
Dim adpt As SqlDataAdapter
Dim conn As String =
ConfigurationManager.ConnectionStrings("DB").ConnectionString
Try
con = New SqlConnection(conn)
adpt = New SqlDataAdapter
com = New SqlCommand
com.Connection = con
com.CommandText = "Select * from CardBought(@UseName)"
com.Parameters.AddWithValue("@UseName", Page.User.Identity.Name)
adpt.SelectCommand = com
dt = New DataTable
adpt.Fill(dt)
GVCard.DataSource = dt
gvCard.DataBind()
lblCount.Text = CStr(gvCard.Rows.Count())
Catch ex As Exception
Response.Write(ex.ToString)
End Try
End Sub
SQL Function to insert data in to Table
USE [BestSuk]
GO
/****** Object: StoredProcedure [dbo].[InsertMyFun]
11/29/2015 09:20:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Script Date:
ALTER Procedure [dbo].[InsertMyFun] (@Customer nvarchar(50),@Category
nvarchar(50),@Newcat nvarchar(50),@NewcatLen as numeric(18,0), @Fun
Nvarchar(2500))
as
declare @ReportedBy as nvarchar (50);
17 | P a g e
declare @Reportedfrom as Nvarchar(50);
declare @Count as numeric(18,0);
Begin
set @Count = 0;
select @reportedBy = FullName from [BestSuk].[dbo].UserMore where UserName =
@Customer;
select @reportedfrom = Country from [BestSuk].[dbo].UserMore where UserName =
@Customer;
if (@NewcatLen >0)
begin
select @count = count (Category) from CategoryF where Category = @Newcat;
end
if (@NewcatLen>0)
begin
if (@Count = 0)
begin
INSERT INTO [BestSuk].[dbo].[CategoryF] ([Category])
VALUES (@Newcat);
INSERT INTO [BestSuk].[dbo].[MyFun]
([Category],[Fun],[PostedBy],[PostedFrom],[PostedTime])
VALUES (@Newcat,
@Fun,@ReportedBy,@Reportedfrom,GETDATE());
end
else
begin
INSERT INTO [BestSuk].[dbo].[MyFun]
([Category],[Fun],[PostedBy],[PostedFrom],[postedTime])
VALUES (@Category,
@Fun,@ReportedBy,@Reportedfrom,GETDATE());
end
end
else
Begin
INSERT INTO [BestSuk].[dbo].[MyFun]
([Category],[Fun],[PostedBy],[PostedFrom],[PostedTime])
VALUES (@Category, @Fun,@ReportedBy,@Reportedfrom,GETDATE());
end
End
SQL Function which add data to a table and returns value this is good for
file Naming getting id of last added record
USE [BestSuk]
GO
/****** Object: StoredProcedure [dbo].[BuyCardeTPay]
11/29/2015 09:24:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Script Date:
18 | P a g e
ALTER Procedure [dbo].[BuyCardeTPay] (@Amount Numeric(18,0), @Customer
nvarchar(50),@Pmode nvarchar(50),
@IDP1 numeric(18,0), @IDPM1 numeric(18,0),@Val1 numeric(18,0),
@IDP2 numeric(18,0), @IDPM2 numeric(18,0),@Val2 numeric(18,0),
@IDP3 numeric(18,0), @IDPM3 numeric(18,0),@Val3 numeric(18,0),
@IDP4 numeric(18,0), @IDPM4 numeric(18,0),@Val4 numeric(18,0),
@IDP5 numeric(18,0), @IDPM5 numeric(18,0),@Val5 numeric(18,0),
@Ecards nvarchar (100), @EPins nvarchar (50),
@Number nvarchar(28)Output,@Serial nvarchar(22) output,@Rand integer output,
@Date date output,@Valid Nvarchar(10)Output, @ID Numeric(18,0) Output)
as
declare
declare
declare
declare
declare
declare
declare
@OId as numeric(18,0);
@Ans as bit;
@Count numeric(18,0);
@Amountneg numeric(18,0);
@UIDD as Uniqueidentifier;
@eStage as nvarchar(10);
@TelID numeric(18,0);
Begin
set @Count = 0;
select @OId = ReferedBy FROM UserMore where UserName =@Customer
select @Count = Count(serial) FROM TelCard where Status ='New' and amount
=@Amount and Owner=@OId
if (@Count = 0)
set @Valid = 'Not Valid'
else
begin
Set @Valid = 'Valid'
select @UIDD = UserID FROM aspnet_Users where UserName =@Customer
select Top 1 @ID = serial FROM TelCard where Status ='New' and amount
=@Amount and Owner=@OId
select @Serial = ID FROM TelCard where Serial =@ID
select @Number = Number FROM TelCard where Serial =@ID
select @Rand = [Rand] FROM TelCard where Serial =@ID
select @Date = ExpierDate FROM TelCard where Serial =@ID
Update TelCard Set PDate = GETDATE(), Status = 'Sold', UseID= @UIDD where
Serial = @Id;
set @Amountneg = @Amount ;
Insert Into CardTransaction
([UserID],[Serial],[Amount],[Purchase_Mode],[etpay_NO], [eTPay_Pin]) values
(@UIDD,@Id,@Amountneg, @Pmode,@Ecards,@EPins)
Insert Into CardLog ([Serial],[Amount],[Action],[UserId],[Ran]) values
(@ID,@Amount,@PMode,@UIDD,@Rand)
if (@IDP1>0)
begin
if (@Val1>0)
begin
set @eStage = 'STARTED'
end
else
begin
set @eStage = 'CONSUMED'
19 | P a g e
end
Update PayerMini Set eUsedDate = GETDATE(), eStage = @eStage,
@Customer, eBalance = @Val1 where MPSerial = @IDPM1;
Update Payer Set Balance = @Val1, Status=@eStage where Serial
end
/*
*************
*/
if (@IDP2>0)
begin
if (@Val2>0)
begin
set @eStage = 'STARTED'
end
else
begin
set @eStage = 'CONSUMED'
end
Update PayerMini Set eUsedDate = GETDATE(), eStage = @eStage,
@Customer, eBalance = @Val2 where MPSerial = @IDPM2;
Update Payer Set Balance = @Val2, Status=@eStage where Serial
end
/*
*************
*/
if (@IDP3>0)
begin
if (@Val3>0)
begin
set @eStage = 'STARTED'
end
else
begin
set @eStage = 'CONSUMED'
end
Update PayerMini Set eUsedDate = GETDATE(), eStage = @eStage,
@Customer, eBalance = @Val3 where MPSerial = @IDPM3;
Update Payer Set Balance = @Val3, Status=@eStage where Serial
end
/*
*************
*/
if (@IDP4>0)
begin
if (@Val4>0)
begin
set @eStage = 'STARTED'
end
else
begin
set @eStage = 'CONSUMED'
end
Update PayerMini Set eUsedDate = GETDATE(), eStage = @eStage,
@Customer, eBalance = @Val1 where MPSerial = @IDPM4;
Update Payer Set Balance = @Val4, Status=@eStage where Serial
end
if (@IDP5>0)
begin
if (@Val5>0)
begin
set @eStage = 'STARTED'
end
else
fUser=
= @IDP1;
fUser=
= @IDP2;
fUser=
= @IDP3;
fUser=
= @IDP4;
20 | P a g e
begin
set @eStage = 'CONSUMED'
end
Update PayerMini Set eUsedDate = GETDATE(), eStage = @eStage, fUser=
@Customer, eBalance = @Val5 where MPSerial = @IDPM5;
Update Payer Set Balance = @Val5, Status=@eStage where Serial = @IDP5;
end
/*
*************
*/
end
end
How to call and receive SQL Function table with returning value
Private Sub TransacteTPay(ByVal pm As String)
Dim con As SqlConnection ' Connection Variable
Dim com As SqlCommand
com = New SqlCommand
Dim com2 As SqlCommand
com2 = New SqlCommand
Dim conn As String =
ConfigurationManager.ConnectionStrings("DB").ConnectionString
con = New SqlConnection(conn)
Dim Cid As Integer
Dim nm, ser As String
Dim c As Integer
Dim dat As Date
Dim eCard, ePin As String
eCard = CStr(lblCn1.Text) & " , " & CStr(lblCn2.Text) & " , " & CStr(lblCn3.Text)
& " , " & CStr(lblCn4.Text) & " , " & CStr(lblCn5.Text)
ePin = CStr(lblPV1.Text) & " , " & CStr(lblPV2.Text) & " , " & CStr(lblPV3.Text)
& " , " & CStr(lblPV4.Text) & " , " & CStr(lblPV5.Text)
'
'@IDP1 numeric(18,0), @IDPM1 numeric(18,0),@Val1 numeric(18,0),
'@IDP2 numeric(18,0), @IDPM2 numeric(18,0),@Val2 numeric(18,0),
'@IDP3 numeric(18,0), @IDPM3 numeric(18,0),@Val3 numeric(18,0),
'@IDP4 numeric(18,0), @IDPM4 numeric(18,0),@Val4 numeric(18,0),
'@IDP5 numeric(18,0), @IDPM5 numeric(18,0),@Val5 numeric(18,0),
'@Ecards nvarchar (100), @EPins nvarchar (50),
'@Number nvarchar(28)Output,@Serial nvarchar(22) output,@Rand integer output,
@Date date output,@Valid Nvarchar(10)Output, @ID Numeric(18,0) Output)
If btneTPayBuy.Text = "eTPay Purchase" Then
con = New SqlConnection(conn)
com.Connection = con
com.CommandText = "BuyCardeTPay"
com.CommandType = CommandType.StoredProcedure
com.Parameters.Add("@Amount", SqlDbType.Int)
com.Parameters("@Amount").Value = CInt(ddCardValue.SelectedValue) '
CInt(txtran.Text) to be replaced by rn
com.Parameters.Add("@Customer", SqlDbType.NVarChar, 50)
com.Parameters("@Customer").Value = Page.User.Identity.Name
com.Parameters.Add("@Pmode", SqlDbType.NVarChar, 50)
com.Parameters("@Pmode").Value = pm
21 | P a g e
com.Parameters.Add("@IDP1", SqlDbType.Int)
com.Parameters("@IDP1").Value = CInt(lblID1.Text)
com.Parameters.Add("@IDP2", SqlDbType.Int)
com.Parameters("@IDP2").Value = CInt(lblID2.Text)
com.Parameters.Add("@IDP3", SqlDbType.Int)
com.Parameters("@IDP3").Value = CInt(lblID3.Text)
com.Parameters.Add("@IDP4", SqlDbType.Int)
com.Parameters("@IDP4").Value = CInt(lblID4.Text)
com.Parameters.Add("@IDP5", SqlDbType.Int)
com.Parameters("@IDP5").Value = CInt(lblID5.Text)
com.Parameters.Add("@IDPM1", SqlDbType.Int)
com.Parameters("@IDPM1").Value = CInt(lblIDPM1.Text)
com.Parameters.Add("@IDPM2", SqlDbType.Int)
com.Parameters("@IDPM2").Value = CInt(lblIDPM2.Text)
com.Parameters.Add("@IDPM3", SqlDbType.Int)
com.Parameters("@IDPM3").Value = CInt(lblIDPM3.Text)
com.Parameters.Add("@IDPM4", SqlDbType.Int)
com.Parameters("@IDPM4").Value = CInt(lblIDPM4.Text)
com.Parameters.Add("@IDPM5", SqlDbType.Int)
com.Parameters("@IDPM5").Value = CInt(lblIDPM5.Text)
com.Parameters.Add("@Val1", SqlDbType.Int)
com.Parameters("@Val1").Value = CInt(lblRMBal1.Text)
com.Parameters.Add("@Val2", SqlDbType.Int)
com.Parameters("@Val2").Value = CInt(lblRMBal2.Text)
com.Parameters.Add("@Val3", SqlDbType.Int)
com.Parameters("@Val3").Value = CInt(lblRMBal3.Text)
com.Parameters.Add("@Val4", SqlDbType.Int)
com.Parameters("@Val4").Value = CInt(lblRMBal4.Text)
com.Parameters.Add("@Val5", SqlDbType.Int)
com.Parameters("@Val5").Value = CInt(lblRMBal5.Text)
'@Ecards nvarchar (100), @EPins nvarchar (50),
'@Number nvarchar(28)Output,@Serial nvarchar(22) output,@Rand integer output,
@Date date output,@Valid Nvarchar(10)Output, @ID Numeric(18,0) Output)
com.Parameters.Add("@ECards", SqlDbType.NVarChar, 100)
com.Parameters("@ECards").Value = eCard
com.Parameters.Add("@EPins", SqlDbType.NVarChar, 50)
com.Parameters("@EPins").Value = ePin
com.Parameters.Add("@Number", SqlDbType.NVarChar, 28)
com.Parameters("@Number").Direction = ParameterDirection.Output
com.Parameters.Add("@Serial", SqlDbType.NVarChar, 22)
22 | P a g e
com.Parameters("@Serial").Direction = ParameterDirection.Output
com.Parameters.Add("@Rand", SqlDbType.Int)
com.Parameters("@Rand").Direction = ParameterDirection.Output
com.Parameters.Add("@Date", SqlDbType.Date)
com.Parameters("@Date").Direction = ParameterDirection.Output
com.Parameters.Add("@Valid", SqlDbType.NVarChar, 10)
com.Parameters("@Valid").Direction = ParameterDirection.Output
com.Parameters.Add("@ID", SqlDbType.Int)
com.Parameters("@ID").Direction = ParameterDirection.Output
Try
con.Open()
com.ExecuteNonQuery()
Dim test As String
test = com.Parameters("@Valid").Value
If test = "Not Valid" Then
lblAvelablity.Text = "Sorry All Cards have been Soled Out"
lblAvelablity.ForeColor = Drawing.Color.Red
lblAvelablity.Visible = True
txtCard.Visible = False
txtSerial.Visible = False
txtExpire.Visible = False
lblCard.Visible = False
lblSerial.Visible = False
lblExpDate.Visible = False
btnBuy.Visible = False
btneTPayBuy.Text = "eTPay Purchase"
Else
nm = com.Parameters("@Number").Value
ser = com.Parameters("@Serial").Value
c = com.Parameters("@Rand").Value
dat = com.Parameters("@Date").Value
Cid = com.Parameters("@ID").Value
c = c Mod 10
If c = 0 Then
c = 1
End If
txtCard.Text = NumC(c, "dec", nm)
txtSerial.Text = SerialC(c, "dec", ser)
txtExpire.Text = dat.ToString
txtCard.Visible = True
txtSerial.Visible = True
txtExpire.Visible = True
lblCard.Visible = True
lblSerial.Visible = True
lblExpDate.Visible = True
btneTPayBuy.Enabled = True
lblAvelablity.Text = "Thank you for buying card from BestSuk"
lblAvelablity.ForeColor = Drawing.Color.Green
btneTPayBuy.Text = "Do you want to buy more card?"
etPayReset()
con.Close()
End If
23 | P a g e
Catch ex As Exception
Response.Write(ex.Message.ToString)
Finally
con.Close()
End Try
Try
con.Open()
com2.Connection = con
com2.CommandText = "TansSerUp"
com2.CommandType = CommandType.StoredProcedure
com2.Parameters.Add("@Number2", SqlDbType.NVarChar)
com2.Parameters("@Number2").Value = txtCard.Text
com2.Parameters.Add("@Serial2", SqlDbType.NVarChar)
com2.Parameters("@Serial2").Value = txtSerial.Text
com2.Parameters.Add("@ID2", SqlDbType.Int)
com2.Parameters("@ID2").Value = Cid
com2.ExecuteNonQuery()
con.Close()
Catch ex As Exception
Response.Write(ex.Message.ToString)
Finally
con.Close()
End Try
Else
txtCard.Visible = False
txtSerial.Visible = False
txtExpire.Visible = False
lblCard.Visible = False
lblSerial.Visible = False
lblExpDate.Visible = False
btneTPayBuy.Enabled = False
btneTPayBuy.Text = "eTPay Purchase"
lblAvelablity.Visible = False
etPayReset()
End If
End Sub
Private Sub TransacteZPay(ByVal pm As String)
Dim con As SqlConnection ' Connection Variable
Dim com As SqlCommand
com = New SqlCommand
Dim com2 As SqlCommand
com2 = New SqlCommand
Dim conn As String =
ConfigurationManager.ConnectionStrings("DB").ConnectionString
con = New SqlConnection(conn)
Dim Cid As Integer
Dim nm, ser As String
Dim c As Integer
Dim dat As Date
Dim eCard, ePin As String
24 | P a g e
'
Create Procedure [dbo].[BuyCardeZPay] (@Balance Numeric(18,2), @Customer
nvarchar(50),@eZName nvarchar(52),@eZPin nvarchar(6),@Pmode nvarchar(50),@Amount
Numeric(18,0),
'@Number nvarchar(28)Output,@Serial nvarchar(22) output,@Rand integer output,
@Date date output,@Valid Nvarchar(10)Output, @ID Numeric(18,0) Output)
If btneZPayBuy.Text = "eZPay Purchase" Then
con = New SqlConnection(conn)
com.Connection = con
com.CommandText = "BuyCardeZPay"
com.CommandType = CommandType.StoredProcedure
com.Parameters.Add("@Amount", SqlDbType.Int)
com.Parameters("@Amount").Value = CInt(ddCardValue.SelectedValue) '
CInt(txtran.Text) to be replaced by rn
com.Parameters.Add("@Balance", SqlDbType.Int)
com.Parameters("@Balance").Value = CInt(lbleZPayRBalance.Text)
com.Parameters.Add("@Customer", SqlDbType.NVarChar, 50)
com.Parameters("@Customer").Value = Page.User.Identity.Name
com.Parameters.Add("@eZName", SqlDbType.NVarChar, 52)
com.Parameters("@eZName").Value = txteZPayName.Text
com.Parameters.Add("@eZPin", SqlDbType.NVarChar, 20)
com.Parameters("@eZPin").Value = lblAnswer.Text
com.Parameters.Add("@Pmode", SqlDbType.NVarChar, 50)
com.Parameters("@Pmode").Value = pm
com.Parameters.Add("@Number", SqlDbType.NVarChar, 28)
com.Parameters("@Number").Direction = ParameterDirection.Output
com.Parameters.Add("@Serial", SqlDbType.NVarChar, 22)
com.Parameters("@Serial").Direction = ParameterDirection.Output
com.Parameters.Add("@Rand", SqlDbType.Int)
com.Parameters("@Rand").Direction = ParameterDirection.Output
com.Parameters.Add("@Date", SqlDbType.Date)
com.Parameters("@Date").Direction = ParameterDirection.Output
com.Parameters.Add("@Valid", SqlDbType.NVarChar, 10)
com.Parameters("@Valid").Direction = ParameterDirection.Output
com.Parameters.Add("@ID", SqlDbType.Int)
com.Parameters("@ID").Direction = ParameterDirection.Output
Try
con.Open()
com.ExecuteNonQuery()
Dim test As String
test = com.Parameters("@Valid").Value
If test = "Not Valid" Then
lblAvelablity.Text = "Sorry All Cards have been Soled Out"
lblAvelablity.ForeColor = Drawing.Color.Red
lblAvelablity.Visible = True
txtCard.Visible = False
txtSerial.Visible = False
25 | P a g e
txtExpire.Visible = False
lblCard.Visible = False
lblSerial.Visible = False
lblExpDate.Visible = False
btnBuy.Visible = False
btneZPayBuy.Text = "eZPay Purchase"
Else
nm = com.Parameters("@Number").Value
ser = com.Parameters("@Serial").Value
c = com.Parameters("@Rand").Value
dat = com.Parameters("@Date").Value
Cid = com.Parameters("@ID").Value
c = c Mod 10
If c = 0 Then
c = 1
End If
txtCard.Text = NumC(c, "dec", nm)
txtSerial.Text = SerialC(c, "dec", ser)
txtExpire.Text = dat.ToString
txtCard.Visible = True
txtSerial.Visible = True
txtExpire.Visible = True
lblCard.Visible = True
lblSerial.Visible = True
lblExpDate.Visible = True
btneZPayBuy.Enabled = True
lblAvelablity.Text = "Thank you for buying card from BestSuk"
lblAvelablity.ForeColor = Drawing.Color.Green
btneZPayBuy.Text = "Do you want to buy more card?"
eZPayReset()
con.Close()
End If
Catch ex As Exception
Response.Write(ex.Message.ToString)
Finally
con.Close()
End Try
Try
con.Open()
com2.Connection = con
com2.CommandText = "TansSerUp"
com2.CommandType = CommandType.StoredProcedure
com2.Parameters.Add("@Number2", SqlDbType.NVarChar)
com2.Parameters("@Number2").Value = txtCard.Text
com2.Parameters.Add("@Serial2", SqlDbType.NVarChar)
com2.Parameters("@Serial2").Value = txtSerial.Text
com2.Parameters.Add("@ID2", SqlDbType.Int)
com2.Parameters("@ID2").Value = Cid
com2.ExecuteNonQuery()
con.Close()
Catch ex As Exception
Response.Write(ex.Message.ToString)
Finally
con.Close()
End Try
26 | P a g e
Else
txtCard.Visible = False
txtSerial.Visible = False
txtExpire.Visible = False
lblCard.Visible = False
lblSerial.Visible = False
lblExpDate.Visible = False
btneTPayBuy.Enabled = False
btneZPayBuy.Text = "eZPay Purchase"
lblAvelablity.Visible = False
etPayReset()
End If
End Sub
'Private Function NumC(ByVal ra As Integer, ByVal dir As String, ByVal txt
Best technique when retrieving document for Editing from SQL
Protected Sub btnViewEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles btnViewEdit.Click
Dim SQL As String
SQL = "Select CourtDoc_ID as C0, UN as C1, DOC_Type as C2, Sub_Doc_Type as
C3,Title as C4, Reference as C5, Case_Number as C6, Author as C7, Contributor as C8,
Applicant as C9, Respondent as C10, Origional_Language as C11, DeadLine as C12, TArabic
as C13, TEnglish as C14, TFrench as C15, TPortuguese as C16, Priority as C17,
Number_Of_Pages as C18, Remark as C19, Confidentiality_Level as C20, word_Count as C21,
RatePer1000Words as C22, ToBeDone as C23, Sub_Date as c24
from documents where
courtdoc_id =" & ddCode.SelectedValue
Dim cmd As New SqlCommand()
Dim UN1, DT2, SDT3, WoC21, NoP18 As Integer
Dim Rate22 As Decimal
Dim DL12, SuB24 As Date
Dim TA13, TE14, TF15, TP16 As Boolean
Dim Ttl4, Ref5, CN6, AuT7, CoN8, App9, Res10, OrL11, PrI17, ReM19, ConF20, ToBe23
As String
Dim dt, mt, yr As Integer
cmd.CommandText = SQL
cmd.Connection = con
Try
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
While reader.Read()
If reader.IsDBNull(1) Then
UN1 = 1
Else
UN1 = CInt(reader.GetDecimal(1))
End If
If reader.IsDBNull(2) Then
DT2 = 1
27 | P a g e
Else
DT2 = CInt(reader.GetDecimal(2))
End If
If reader.IsDBNull(3) Then
SDT3 = 1
Else
SDT3 = CInt(reader.GetDecimal(3))
End If
If reader.IsDBNull(4) Then
Ttl4 = ""
Else
Ttl4 = reader.GetString(4)
End If
If reader.IsDBNull(5) Then
Ref5 = ""
Else
Ref5 = reader.GetString(5)
End If
If reader.IsDBNull(6) Then
CN6 = ""
Else
CN6 = reader.GetString(6)
End If
If reader.IsDBNull(7) Then
AuT7 = ""
Else
AuT7 = reader.GetString(7)
End If
If reader.IsDBNull(8) Then
CoN8 = ""
Else
CoN8 = reader.GetString(8)
End If
If reader.IsDBNull(9) Then
App9 = ""
Else
App9 = reader.GetString(9)
End If
If reader.IsDBNull(10) Then
Res10 = ""
Else
Res10 = reader.GetString(10)
End If
If reader.IsDBNull(11) Then
OrL11 = "English"
Else
OrL11 = reader.GetString(11)
End If
If reader.IsDBNull(12) Then
DL12 = Now()
Else
DL12 = reader.GetSqlDateTime(12)
End If
If reader.IsDBNull(13) Then
TA13 = "False"
Else
TA13 = reader.GetBoolean(13)
End If
28 | P a g e
If reader.IsDBNull(14) Then
TE14 = "False"
Else
TE14 = reader.GetBoolean(14)
End If
If reader.IsDBNull(15) Then
TF15 = "False"
Else
TF15 = reader.GetBoolean(15)
End If
If reader.IsDBNull(16) Then
TP16 = "False"
Else
TP16 = reader.GetBoolean(16)
End If
If reader.IsDBNull(17) Then
PrI17 = "Normal"
Else
PrI17 = reader.GetString(17)
End If
If reader.IsDBNull(18) Then
NoP18 = 0
Else
NoP18 = CInt(reader.GetDecimal(18))
End If
If reader.IsDBNull(19) Then
ReM19 = ""
Else
ReM19 = reader.GetString(19)
End If
If reader.IsDBNull(20) Then
ConF20 = "unit"
Else
ConF20 = reader.GetString(20)
End If
If reader.IsDBNull(21) Then
WoC21 = 0
Else
WoC21 = CInt(reader.GetDecimal(21))
End If
If reader.IsDBNull(22) Then
Rate22 = 0
Else
Rate22 = CDec(reader.GetDecimal(22))
End If
If reader.IsDBNull(23) Then
ToBe23 = "IN-House"
Else
ToBe23 = reader.GetString(23)
End If
If reader.IsDBNull(24) Then
SuB24 = Now()
Else
SuB24 = reader.GetSqlDateTime(24)
End If
End While
reader.Close()
29 | P a g e
Catch ex As Exception
Response.Write("Error in Getting the Editable fields" & ex.ToString)
Finally
con.Close()
End Try
dt = Day(DL12)
mt = Month(DL12)
yr = Year(DL12)
ddUnit.SelectedValue = UN1
ddDocCat.SelectedValue = DT2
ddDocCat_SelectedIndexChanged(sender, e)
ddDocSubCat.SelectedValue = SDT3
txtTitle.Text = Ttl4
txtReference.Text = Ref5
txtCaseNo.Text = CN6
txtAuthor.Text = AuT7
txtContributor.Text = CoN8
txtApplicant.Text = App9
txtRespondent.Text = Res10
ddDate.SelectedValue = dt
ddmonth.SelectedValue = mt
ddYear.SelectedValue = yr
ddlan.SelectedValue = OrL11
ckArabic.Checked = TA13
ckEnglish.Checked = TE14
CKFrench.Checked = TF15
ckPortuguese.Checked = TP16
ddPriority.SelectedValue = PrI17
txtPage.Text = NoP18
txtRemark.Text = ReM19
ddConf.SelectedValue = ConF20
txtWordCount.Text = WoC21
txtRate.Text = Rate22
ddtoBeDone.SelectedValue = ToBe23
lblSubmission.Text = CStr(SuB24)
Response.Write(UN1 & " , " & DT2 & " , " & SDT3 & " , " & Ttl4 & " , " & Ref5 & "
, " & CN6)
End Sub
How to Trim Ending and Leading Spaces in SQL Server
Update MSSummitDoc SET Reference = RTRIM(LTRIM(Reference))
Download