Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





'declare' Syntax In A UDF


Hi, I'm trying to create a function that returns a table, however I want
to use a local variable in there and enterprise manager ain't liking it!

The error I get is number 156 'incorrect syntax near the keyword
'declare'.. hopefully this is just a simple thing where I've put it in
the wrong place.

The code follows:

CREATE FUNCTION AFGroupedTotals (@campaign nvarchar(30),@datefrom
smalldatetime, @dateto smalldatetime, @prospect nvarchar(30), @type
nvarchar(20))

RETURNS TABLE AS
RETURN

declare @set nvarchar(150)

select "Total Pledged" as info, sum(total) as tot
FROM AFresponseTotals (@campaign, @datefrom, @dateto,@prospect)


Cheers for any help,
Chris




View Complete Forum Thread with Replies

Related Forum Messages:
Syntax Error On Declare.
 
I am trying to create a view or a table with in SQL system and it keeps coming up with incorrect syntax near the word declare.
It runs fine as long as I do not try and create a table or a view, which unfortunatly I need to do as I have to export the data into Excel for the finance guys.
 
 
The syntax is below....
 

Create View dbo.Z_Cashflow_Forc_Paymsdue
As
Declare @Firstday Int
Declare @Nextday Int
Set @Firstday = '10'
Set @Nextday = '25'
Select [Supplier Code], [Supplier Name], Stype, [Order No], [Line No], [Due Date], [Mat Part], [Qty Ordered], [Purch Price], [Value], Dateadd(dd,Screditdays,[Due Date]) as [Paym Date], Letype, Lecurcode,
Case
When Datepart(Dd, Dateadd(dd,Screditdays,[Due Date])) < '10' then Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday, Dateadd(dd,Screditdays,[Due Date]))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '10' and Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) < '25' then Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Nextday, Dateadd(dd,Screditdays,[Due Date]))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) < '12' then Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(dateadd(mm,1,Dateadd(dd,Screditdays,[Due Date]))))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) = '12' then Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(Dateadd(mm,1,DateAdd(yyyy,1,Dateadd(dd,Screditdays,[Due Date])))))
End AS [Paymdate],
Case
When Datepart(Dd, Dateadd(dd,Screditdays,[Due Date])) < '10' then Datepart(wk,Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday, Dateadd(dd,Screditdays,[Due Date])))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '10' and Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) < '25' then Datepart(wk,Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Nextday, Dateadd(dd,Screditdays,[Due Date])))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) < '12' then Datepart(wk,Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(dateadd(mm,1,Dateadd(dd,Screditdays,[Due Date])))))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) = '12' then Datepart(wk,Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(Dateadd(mm,1,DateAdd(yyyy,1,Dateadd(dd,Screditdays,[Due Date]))))))
End AS [PaymWk],
Case
When Datepart(Dd, Dateadd(dd,Screditdays,[Due Date])) < '10' then Datepart(yyyy,Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday, Dateadd(dd,Screditdays,[Due Date])))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '10' and Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) < '25' then Datepart(yyyy,Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Nextday, Dateadd(dd,Screditdays,[Due Date])))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) < '12' then Datepart(yyyy,Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(dateadd(mm,1,Dateadd(dd,Screditdays,[Due Date])))))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) = '12' then Datepart(yyyy,Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(Dateadd(mm,1,DateAdd(yyyy,1,Dateadd(dd,Screditdays,[Due Date]))))))
End AS [PaymYr]
from Z_Cashflow_Purchorders, Wsuppliers
Where [Supplier Code] = Supp

Union

Select [Supplier Code], [Supplier Name], Stype, [Order No], [Line No], [Due Date], [Mat Part], [Qty Ordered], [Purch Price], [Value], Dateadd(dd,Screditdays,[Due Date]) as [Paym Date], Letype, Lecurcode,
Case
When Datepart(Dd, Dateadd(dd,Screditdays,[Due Date])) < '10' then Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday, Dateadd(dd,Screditdays,[Due Date]))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '10' and Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) < '25' then Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Nextday, Dateadd(dd,Screditdays,[Due Date]))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) < '12' then Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(dateadd(mm,1,Dateadd(dd,Screditdays,[Due Date]))))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) = '12' then Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(Dateadd(mm,1,DateAdd(yyyy,1,Dateadd(dd,Screditdays,[Due Date])))))
End AS [Paymdate],
Case
When Datepart(Dd, Dateadd(dd,Screditdays,[Due Date])) < '10' then Datepart(wk,Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday, Dateadd(dd,Screditdays,[Due Date])))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '10' and Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) < '25' then Datepart(wk,Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Nextday, Dateadd(dd,Screditdays,[Due Date])))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) < '12' then Datepart(wk,Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(dateadd(mm,1,Dateadd(dd,Screditdays,[Due Date])))))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) = '12' then Datepart(wk,Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(Dateadd(mm,1,DateAdd(yyyy,1,Dateadd(dd,Screditdays,[Due Date]))))))
End AS [PaymWk],
Case
When Datepart(Dd, Dateadd(dd,Screditdays,[Due Date])) < '10' then Datepart(yyyy,Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday, Dateadd(dd,Screditdays,[Due Date])))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '10' and Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) < '25' then Datepart(yyyy,Dateadd(dd, - Day(Dateadd(dd,Screditdays,[Due Date])) + @Nextday, Dateadd(dd,Screditdays,[Due Date])))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) < '12' then Datepart(yyyy,Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(dateadd(mm,1,Dateadd(dd,Screditdays,[Due Date])))))
When Datepart(dd, Dateadd(dd,Screditdays,[Due Date])) >= '25' and Datepart(mm, Dateadd(dd,Screditdays,[Due Date])) = '12' then Datepart(yyyy,Dateadd(dd, - day(Dateadd(dd,Screditdays,[Due Date])) + @Firstday,(Dateadd(mm,1,DateAdd(yyyy,1,Dateadd(dd,Screditdays,[Due Date]))))))
End AS [PaymYr]
from Z_Cashflow_Schedorders, Wsuppliers
Where [Supplier Code] = Supp

View Replies !
Incorrect Syntax Near The Keyword 'Declare'.
Dear Group,I am trying to create a view and keep getting the Incorrect syntax near thekeyword 'Declare'" error.Here is the code I am writing.Create view fixed_airs (sid, fad_a2, fad_a3) asDeclare @sid int,@fad_a2 int,@fad_a3 intselect @sid=cast(substring(subject_id,1,8)as int) ,@fad_a2 =cast (substring(fad_2_4,1,1) as int),@fad_a3=cast(substring(fad_2_4,2,1) as int)from parentpacket.Thanks for the help in advance.Jeff Magouirk

View Replies !
Incorrect Syntax Near 'nvarchar'. Must Declare The Scalar Variable &"@CODE&".
I have this issue and I can not figure out the problem. I have 4 other forms from the same database using practly the same code, slight variations based on datavalidation requirements. IIS6 SQL Express 2005.
 
I have tried to defint eh colum for CODE as a bound filed and as a templated field. I get the same error.ASPX Page <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="MaintainBSP.aspx.cs" Inherits="MaintainBSP" Title="Maintain BSP Codes" %>
<%@ MasterType VirtualPath="~/Site.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><br />
<table class="mainTable" cellspacing="0" cellpadding="3" align="center">
<tr><td class="mainTableTitle">BSP Codes</td></tr>
<tr><td>
<table align="center">
<tr>
<td><asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"BorderColor="Silver"
BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center"
CellPadding="3"DataKeyNames="CODE" DataMember="DefaultView"
DataSourceID="SqlDataSource1"
OnRowEditing="GridView1_OnRowEditing"
OnRowCancelingEdit="GridView1_EndEdit"
OnRowUpdated="GridView1_EndEdit">
<Columns>
<asp:CommandField ShowEditButton="True" EditText="Edit" CancelText="Cancel" UpdateText="Update" HeaderStyle-CssClass="rptTblTitle" >
<HeaderStyle CssClass="rptTblTitle"></HeaderStyle>
</asp:CommandField>
<asp:BoundField DataField="CODE" HeaderText="Code" ReadOnly="true" HeaderStyle-CssClass="rptTblTitle" />
<asp:TemplateField HeaderText="Bottle Size" SortExpression="Btl Sz">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" MaxLength="10" Columns="10" runat="server" Text='<%# Bind("[BOTTLE$SIZE]") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Bottle Size is a required field." Text="*" ControlToValidate="TextBox1"></asp:RequiredFieldValidator><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Bottle size must be a number followed by 'ML' or 'L'" Text="*" ControlToValidate="TextBox1"
ValidationExpression="[0-9.]+(ML|L)"></asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("[BOTTLE$SIZE]") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="rptTblTitle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Labeled" SortExpression="Labeled">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" MaxLength="1" Columns="2" runat="server" Text='<%# Bind("LABELED") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Labeled is a required field" Text="*" ControlToValidate="TextBox2"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("LABELED") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="rptTblTitle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Bottles Per Case" SortExpression="Btls Per Case">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" Columns="4" runat="server" Text='<%# Bind("[BOTTLES$PER$CASE]") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Bottles per case must be a whole number." Text="*" ControlToValidate="TextBox3"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("[BOTTLES$PER$CASE]") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="rptTblTitle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Liters Per Case" SortExpression="Ltrs Per Case">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" MaxLength="8" Columns="8" runat="server" Text='<%# Bind("[LITERS$PER$CASE]") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Liters per case must be a number." ControlToValidate="TextBox4" Text="*"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("[LITERS$PER$CASE]") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="rptTblTitle" />
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" DeleteText="Delete" HeaderStyle-CssClass="rptTblTitle" >
<HeaderStyle CssClass="rptTblTitle"></HeaderStyle>
</asp:CommandField>
</Columns>
 
</asp:GridView>
 
<table id="tblAddBSP" runat="server" width="100%">
<tr><td colspan="2" align="center"><asp:Label ID="lblAddMessage" runat="server" Text="" style="color:Red;font-weight:bold;"/></td></tr>
<tr>
<td style="font-weight:bold;">Code</td>
<td><asp:TextBox ID="txtAddCode" runat="server" MaxLength="1" Columns="2"></asp:TextBox><asp:RequiredFieldValidator ID="rfv_txtAddCode" runat="server" ErrorMessage="Please Supply a BSP Code." Text="*"
ControlToValidate="txtAddCode" SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="font-weight:bold;">Bottle Size</td>
<td><asp:TextBox ID="txtAddSize" runat="server" MaxLength="10" Columns="10"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Bottle Size is a required field." Text="*" ControlToValidate="txtAddSize"></asp:RequiredFieldValidator><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Bottle size must be a number followed by 'ML' or 'L'" Text="*" ControlToValidate="txtAddSize"
ValidationExpression="[0-9.]+(ML|L)"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td style="font-weight:bold;">Labeled</td>
<td><asp:TextBox ID="txtAddLabeled" runat="server" MaxLength="1" Columns="2"></asp:TextBox></td>
</tr>
<tr>
<td style="font-weight:bold;">Bottles Per Case</td>
<td><asp:TextBox ID="txtAddBottlesPerCase" runat="server" MaxLength="4" Columns="4"></asp:TextBox></td>
</tr>
<tr>
<td style="font-weight:bold;">Liters Per Case</td>
<td><asp:TextBox ID="txtAddLitersPerCase" runat="server" MaxLength="8" Columns="8"></asp:TextBox></td>
</tr><tr><td colspan="2" align="right"><asp:Button ID="btnAddNew" runat="server"
Text="Add BSP" onclick="btnAddNew_Click" /></td></tr>
</table>
</td>
</tr>
</table>
</td></tr>
</table><asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" ShowSummary="False" /><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SqlConnectionString %>"
ProviderName="<%$ ConnectionStrings:SqlConnectionString.ProviderName %>"DeleteCommand="DELETE FROM BSP WHERE CODE = @CODE" InsertCommand="INSERT INTO BSP (CODE, BOTTLE$SIZE, LABELED, BOTTLES$PER$CASE, LITERS$PER$CASE) VALUES (@CODE, @BOTTLE$SIZE, @LABELED, @BOTTLES$PER$CASE, @LITERS$PER$CASE)"
SelectCommand="SELECT CODE, BOTTLE$SIZE, LABELED, BOTTLES$PER$CASE, LITERS$PER$CASE FROM BSP order by CODE"
UpdateCommand="UPDATE BSP SET BOTTLE$SIZE = @BOTTLE$SIZE, LABELED = @LABELED, BOTTLES$PER$CASE = @BOTTLES$PER$CASE, LITERS$PER$CASE = @LITERS$PER$CASE WHERE [CODE] = @CODE">
<UpdateParameters>
<asp:Parameter Name="BOTTLE$SIZE" type="String" />
<asp:Parameter Name="LABELED" type="Char" />
<asp:Parameter Name="BOTTLES$PER$CASE" type="Int32" />
<asp:Parameter Name="LITERS$PER$CASE" type="Decimal" />
<asp:Parameter Name="CODE" type="Char" />
</UpdateParameters>
<InsertParameters>
<asp:ControlParameter ControlID="txtAddSize" Name="BOTTLE$SIZE" type="String" />
<asp:ControlParameter ControlID="txtAddLabeled" Name="LABELED" type="Char" />
<asp:ControlParameter ControlID="txtAddBottlesPerCase" Name="BOTTLES$PER$CASE" type="Int32" />
<asp:ControlParameter ControlID="txtAddLitersPerCase" Name="LITERS$PER$CASE" type="Decimal" />
<asp:ControlParameter ControlID="txtAddCode" Name="CODE" type="Char" />
</InsertParameters>
</asp:SqlDataSource>
 
</asp:Content>
 
CODE BEHIND
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using reports;
using System.Data.SqlClient;
public partial class MaintainBSP : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e)
{Master.ActiveTab = Helpers.Tabs.Admin;Security.CheckPageAccess(Security.AccessTypes.Administrator);
}protected void GridView1_OnRowEditing(Object sender, GridViewEditEventArgs e)
{tblAddBSP.Visible = false;
}protected void GridView1_EndEdit(Object sender, EventArgs e)
{tblAddBSP.Visible = true;
}protected void btnAddNew_Click(object sender, EventArgs e)
{
try
{
SqlDataSource1.Insert();lblAddMessage.Text = "Add BSP '" + txtAddCode.Text + "' successful.";
txtAddCode.Text = String.Empty;txtAddSize.Text = String.Empty;
txtAddLabeled.Text = String.Empty;txtAddBottlesPerCase.Text = String.Empty;txtAddLitersPerCase.Text = String.Empty;
}catch (SqlException ex)
{if (ex.Number == 2627)
{
lblAddMessage.Text = "The code '" + txtAddCode.Text + "' is already in the database.<br />Select another code for this BSP.";txtAddCode.Text = String.Empty;
}
elselblAddMessage.Text = ex.Number + " - " + ex.ErrorCode.ToString() + " - " + ex.Message;
}
catch
{lblAddMessage.Text = "There was an issue inserting the BSP Code '" + txtAddCode.Text + "'. Please check the values and try again.";
}
}
}
 

View Replies !
Converting Oracle Cursor Syntax Into Sql Server Syntax
declare
-- Test statements here
/* ------------------------------------------------------------*/
/* Procedure to update Person / Org without either
a card issue date (ATTRIBUTE9)
a card expiry date (ATTRIBUTE11)

The new card issue date would be set to SYSDATE
The new card expiry date would be set to SYSDATE + 12 months
or SYSDATE + 6 months depends on customer's incentive Level.

Selection C - Not Archived / either Attribute9 or/and Attribute11
IS NULL

Author Version Date Description
------------------------------------------------------------
Emer Ryan (Detica) 0.1 19Mar2004 Initial Version
*/
/* ------------------------------------------------------------*/


CURSOR cur_BLANK IS
SELECT P.PARTY_ID,
ca.account_number,
p.attribute2, ---Incentive Level
p.attribute9, ---card Issue date
p.attribute11, ---card renewal date
p.attribute7,
p.attribute15, ---Internal Status
p.attribute6, ---Card Status
p.last_updated_by,
P.LAST_UPDATE_DATE
from hz_cust_accounts ca, hz_parties p
where ca.party_id = p.party_id and
(p.attribute15 <> 'ARC' or p.attribute15 is null) and
ca.account_number is not null and
p.attribute2 IN ('Upper Tier', 'Lower Tier', 'Inactive') and
(p.attribute9 is null OR p.attribute11 is null);

row_count number := 0;
total_rec number := 0;
begin
-- OUPTUT THE START TIME
DBMS_OUTPUT.PUT_LINE('Running - UPDATE_BLANK card issue/ card renewal date');
DBMS_OUTPUT.PUT_LINE('-- Started at ' || TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS'));
/*enforced cursor to check if customers card issue date and card expiry date is blank when customers
incentive level is Inactive*/
for i in cur_blank loop

/* IF 1 - Inactive Customers */
if i.attribute2 = 'Inactive' then
if i.attribute9 is null and i.attribute11 is null then

/* Update both Card Issue and Card Expiry Dates */
update ar.hz_parties
set attribute9 = to_char(sysdate, 'DDMMYYYY'),
attribute11 = to_char(add_months(sysdate, 6), 'DDMMYYYY'),
last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
end if;
if i.attribute9 is null and i.attribute11 is not null then

/* Update Card Issue Date */
update ar.hz_parties
set attribute9 = to_char(sysdate, 'DDMMYYYY'),
last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
end if;
if i.attribute9 is not null and i.attribute11 is null then

/* Update Card Expiry Dates */
update ar.hz_parties
set attribute11 = to_char(add_months(sysdate,6),
'DDMMYYYY'),
Last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
end if;
end if;

/* IF 1 - Lower Customers */
IF i.attribute2 = 'Lower Tier' then
if i.attribute9 is null and i.attribute11 is null then

/* Update Card Status, Card Issue and Card Expiry Dates */
update ar.hz_parties
set attribute9 = to_char(sysdate, 'DDMMYYYY'),
attribute11 = to_char(add_months(sysdate,12),
'DDMMYYYY'),
attribute6 = 'RLL',
Last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
end if;
if i.attribute9 is null and i.attribute11 is not null then

/* Update Card Issue Date */
update ar.hz_parties
set attribute9 = to_char(sysdate, 'DDMMYYYY'),
attribute6 = 'RLL',
Last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
end if;
if i.attribute9 is not null and i.attribute11 is null then

/* Update Card Statu and Card Expiry Date */
update ar.hz_parties
set attribute11 = to_char(add_months(sysdate,12),
'DDMMYYYY'),
attribute6 = 'RLL',
Last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
end if;
end if;

/* IF 1 - Upper Customers */
if i.attribute2 = 'Upper Tier' then
if i.attribute9 is null and i.attribute11 is null then

/* Update Card Status, Card Issue and Card Expiry Dates */
update ar.hz_parties
set attribute9 = to_char(sysdate, 'DDMMYYYY'),
attribute11 = to_char(add_months(sysdate, 12),
'DDMMYYYY'),
attribute6 = 'RUU',
Last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
end if;
if i.attribute9 is null and i.attribute11 is not null then

/* Update Card Issue Date */
update ar.hz_parties
set attribute9 = to_char(sysdate, 'DDMMYYYY'),
attribute6 = 'RUU',
Last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
end if;
if i.attribute9 is not null and i.attribute11 is null then
update ar.hz_parties
set attribute11 = to_char(add_months(sysdate,12),
'DDMMYYYY'),
attribute6 = 'RUU',
Last_updated_by = '100000001',
LAST_UPDATE_DATE = sysdate
where PARTY_ID = i.party_id;
row_count := row_count + 1;
total_rec := total_rec + 1;
END IF;

/* IF 2 - Commit loop */
if row_count = 1000 then
commit;
row_count := 0;
end if;
/* -- IF 2 - END */
end IF;
/* IF 1 - END */

END LOOP;
COMMIT;

dbms_output.put_line('-- Total rec updated ' || total_rec);
dbms_output.put_line('-- Ended at ' || TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS'));
-- Standard Exception Handling
-- Handled by call to external procedure

-- EXIT 0;

EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
DBMS_OUTPUT.PUT_LINE('ERROR - Data Patch Error ' || 'Code:' || SQLCODE ||
'Error ' || SQLERRM);

-- EXIT 1;

end;
/
--exit '0'
EXIT;

View Replies !
Incorrect Syntax Near The Keyword CONVERT When The Syntax Is Correct - Why?
Why does the following call to a stored procedure get me this error:
 

Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'CONVERT'.
 



Code Snippet

EXECUTE OpenInvoiceItemSP_RAM CONVERT(DATETIME,'01-01-2008'), CONVERT(DATETIME,'04/30/2008') , 1,'81350'
 



The stored procedure accepts two datetime parameters, followed by an INT and a varchar(10) in that order.
 
I can't find anything wrong in the syntax for CONVERT or any nearby items.

 
Help me please. Thank you.

View Replies !
Declare @var????
I am trying to get a grasp on the Sql Stored procedures it seems i dont really understnad what DECLARE @Date DateTime means??? I mean i think it means that i am just declaring a varible name Date that will hold a DateTime Value??? is that correct or is it more to it????

CREATE PROCEDURE dbo.Tracking_GetStatus
AS
 DECLARE @Date DateTime
 DECLARE @Begining DateTime
 DECLARE @Ending DateTime
 
 SET @Date = GETDATE()
 SET @Begining = DATEADD(ss,(DATEPART(ss,@Date)*-1),
     DATEADD(mi,(DATEPART(mi,@Date)*-1),
     DATEADD(hh,(DATEPART(hh,@Date)*-1),@Date)))
 SET @Ending   = DATEADD(ss,-1,
     DATEADD(dd,1,DATEADD(ss,(DATEPART(ss,@Date)*-1),
     DATEADD(mi,(DATEPART(mi,@Date)*-1),
     DATEADD(hh,(DATEPART(hh,@Date)*-1),@Date)))))

 SELECT
  Vehicl,
  UpdateTi
  XCoord,
  YCoord,
  Status
 FROM Track
 WHERE UpdateTime >= @Begining
  AND UpdateTime <= @Ending
RETURN


GO
 
 

View Replies !
DECLARE In SQL CE
Can I use DECLARE in SQL 2005 Compact, and if not, how do I do INSERTs into tables which have columns with Primary Key constraints?
 
Matt

View Replies !
Incorrect Syntax When There Appears To Be No Syntax Errors.
I keep receiving the following error whenever I try and call this function to update my database.

The code was working before, all I added was an extra field to update.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'


Public Sub MasterList_Update(sender As Object, e As DataListCommandEventArgs)

Dim strProjectName, txtProjectDescription, intProjectID, strProjectState as String
Dim intEstDuration, dtmCreationDate, strCreatedBy, strProjectLead, dtmEstCompletionDate as String

strProjectName = CType(e.Item.FindControl("txtProjectName"), TextBox).Text
txtProjectDescription = CType(e.Item.FindControl("txtProjDesc"), TextBox).Text
strProjectState = CType(e.Item.FindControl("txtStatus"), TextBox).Text
intEstDuration = CType(e.Item.FindControl("txtDuration"), TextBox).Text
dtmCreationDate = CType(e.Item.FindControl("txtCreation"),TextBox).Text
strCreatedBy = CType(e.Item.FindControl("txtCreatedBy"),TextBox).Text
strProjectLead = CType(e.Item.FindControl("txtLead"),TextBox).Text
dtmEstCompletionDate = CType(e.Item.FindControl("txtComDate"),TextBox).Text
intProjectID = CType(e.Item.FindControl("lblProjectID"), Label).Text

Dim strSQL As String
strSQL = "Update tblProject " _
& "Set strProjectName = @strProjectName, " _
& "txtProjectDescription = @txtProjectDescription, " _
& "strProjectState = @strProjectState, " _
& "intEstDuration = @intEstDuration, " _
& "dtmCreationDate = @dtmCreationDate, " _
& "strCreatedBy = @strCreatedBy, " _
& "strProjectLead = @strProjectLead, " _
& "dtmEstCompletionDate = @dtmEstCompletionDate, " _
& "WHERE intProjectID = @intProjectID"

Dim myConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionstring"))
Dim cmdSQL As New SqlCommand(strSQL, myConnection)

cmdSQL.Parameters.Add(new SqlParameter("@strProjectName", SqlDbType.NVarChar, 40))
cmdSQL.Parameters("@strProjectName").Value = strProjectName
cmdSQL.Parameters.Add(new SqlParameter("@txtProjectDescription", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@txtProjectDescription").Value = txtProjectDescription
cmdSQL.Parameters.Add(new SqlParameter("@strProjectState", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@strProjectState").Value = strProjectState
cmdSQL.Parameters.Add(new SqlParameter("@intEstDuration", SqlDbType.NVarChar, 60))
cmdSQL.Parameters("@intEstDuration").Value = intEstDuration
cmdSQL.Parameters.Add(new SqlParameter("@dtmCreationDate", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@dtmCreationDate").Value = dtmCreationDate
cmdSQL.Parameters.Add(new SqlParameter("@strCreatedBy", SqlDbType.NVarChar, 10))
cmdSQL.Parameters("@strCreatedBy").Value = strCreatedBy
cmdSQL.Parameters.Add(new SqlParameter("@strProjectLead", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@strProjectLead").Value = strProjectLead
cmdSQL.Parameters.Add(new SqlParameter("@dtmEstCompletionDate", SqlDbType.NVarChar, 24))
cmdSQL.Parameters("@dtmEstCompletionDate").Value = dtmEstCompletionDate
cmdSQL.Parameters.Add(new SqlParameter("@intProjectID", SqlDbType.NChar, 5))
cmdSQL.Parameters("@intProjectID").Value = intProjectID

myConnection.Open()
cmdSQL.ExecuteNonQuery
myConnection.Close()

MasterList.EditItemIndex = -1
BindMasterList()


End Sub

Thankyou in advance.

View Replies !
Which Is Faster? Conditional Within JOIN Syntax Or WHERE Syntax?
Forgive the noob question, but i'm still learning SQL everyday and was wondering which of the following is faster? I'm just gonna post parts of the SELECT statement that i've made changes to:

INNER JOIN Facilities f ON e.Facility = f.FacilityID AND f.Name = @FacilityName

OR

WHERE f.Name = @FacilityName


My question is whether or not the query runs faster if i put the condition within the JOIN line as opposed to putting in the WHERE line? Both ways seems to return the same results but the time difference between methods is staggering? Putting the condition within the JOIN line makes the query run about 3 times faster?

Again, forgive my lack of understanding, but could someone agree or disagree and give me the cliff-notes version of why or why not?

Thanks!

View Replies !
Converting Rrom Access Syntax To Sql Syntax
 
Ok I am tying to convert access syntax to Sql syntax to put it in a stored procedure or view..
Here is the part that I need to convert:
 
SELECT [2007_hours].proj_name, [2007_hours].task_name, [2007_hours].Employee,
 IIf(Mid([task_name],1,3)='PTO','PTO_Holiday',
             IIf(Mid([task_name],1,7)='Holiday','PTO_Holiday',
                         IIf(Mid([proj_name],1,9) In ('9900-2831','9900-2788'),'II Internal',
                                     IIf(Mid([proj_name],1,9)='9900-2787','Sales',
                                                 IIf(Mid([proj_name],1,9)='9910-2799','Sales',
                                                             IIf(Mid([proj_name],1,9)='9920-2791','Sales',
                                                                                                                                                
                                                            )
                                                )
                                    )
                        )
            ) AS timeType, Sum([2007_hours].Hours) AS SumOfHours
   from................
 
how can you convert it to sql syntax
 
I need to have a nested If statment which I can't do in sql (in sql I have to have select and from Together for example ( I can't do this in sql):
select ID, FName, LName
if(SUBSTRING(FirstName, 1, 4)= 'Mike')
Begin
    Replace(FirstNam,'Mike','MikeTest')
       if(SUBSTRING(LastName, 1, 4)= 'Kong')
         Begin
            Replace(LastNam,'Kong,'KongTest')
              if(SUBSTRING(Address, 1, 4)= '1245')
             Begin
                 .........
    End
   End

end

 
 
 
 Case Statement might be the solution but i could not do it.
 
 
 
 
 
 
Your input will be appreciated
 
Thank you

View Replies !
My DropDownList Won't Declare?
 Need a little help! I am trying to insert ListItems values from a DropDownList into a database table. However in the code behind I am continuosly met with the error Name 'ddltest' is not declared. As you can see from the code below ddltest is an object with the ID ddltest. What am I doing wrong?
 Protected Sub ddltest_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)Dim MyVar As String = ddltest.SelectedItem.Value
 
If MyVar = "" Then
ErrorMessage.Text = "Please select a test"
Else
'Insert selection into databaseDim oConnection As New SqlConnection
Dim oCommand As SqlCommand
Dim sConnString As String
Dim sSQL As String
sConnString = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|xxxxx.mdf;Integrated Security=True;User Instance=false"oConnection = New SqlConnection(sConnString)
sSQL = "INSERT INTO testDB(Myxxxx) Values (@Myxxxx)"
oConnection.Open()oCommand = New SqlCommand(sSQL, oConnection)oCommand.Parameters.Add(New SqlParameter("@Myxxxx", MyVar))
oCommand.ExecuteNonQuery()
oConnection.Close()
ErrorMessage.Text = "You selected " & MyVar & " and it has been added to the database."
End If
End Sub
 
<asp:TemplateField HeaderText="Test">
<EditItemTemplate>
 
<asp:DropDownList ID="ddltest" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddltest_SelectedIndexChanged" >
<asp:ListItem Selected="True" Value="" ><-- Please Select a test --></asp:ListItem><asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="5" >5</asp:ListItem>
</asp:DropDownList>
 
</EditItemTemplate>
</asp:TemplateField>

View Replies !
Must Declare Scalar @.....
Hi everyone,
I am getting that infamous message on an INSERT Sql query. I am doing everything right by the looks of it. All variables are either passed in through a custom form, or else declared and initialised  in the body of the script.
I post the relevent code below:
SQLsqlInsertEmail = "INSERT INTO CandidateLogins (SiteID, LoginName, CandidateEmail, DateRegistered) " & _" VALUES (@SiteID, @LoginName, @CandidateEmail, @DateRegistered); SELECT SCOPE_IDENTITY()"Try    sqlSetCandidateEmail.Parameters.Add(New SqlParameter("@SiteID", SqlDbType.Int))    sqlSetCandidateEmail.Parameters("@SiteID").Value = SiteID    sqlSetCandidateEmail.Parameters.Add(New SqlParameter("@LoginName", SqlDbType.VarChar))    sqlSetCandidateEmail.Parameters("@LoginName").Value = userName    sqlSetCandidateEmail.Parameters.Add(New SqlParameter("@CandidateEmail", SqlDbType.VarChar))    sqlSetCandidateEmail.Parameters("@CandidateEmail").Value = email    sqlSetCandidateEmail.Parameters.Add(New SqlParameter("@DateRegistered", SqlDbType.DateTime))    sqlSetCandidateEmail.Parameters("@DateRegistered").Value = DateRegistered    sqlSetCandidateEmail = New SqlCommand(sqlInsertEmail, C4LConnection)
    C4LConnection.Open()    CandidateID = sqlSetCandidateEmail.ExecuteScalar()
Catch Exp As SqlException    lblResults.Visible = True    lblResults.Text = "Unable to Register Jobseeker: " & Exp.MessageFinallyC4LConnection.Close()End Try
All the variables passed into the SQL statement are initialised, with SiteID beign set to '0', rather than Null (none of the fields are Nullable in the database table) and I have checked that the SqlDbType's correspend to the Table Definition 
So far as I can discern, everything is correct and as can be seen, I am not using a stored procedure in this instance, but the script falls over be producing the error message "Must Declare Scalar @SiteID", even though SiteID is declared as Int32 further up in the script.
Any help would be appreciated.

View Replies !
How Do I Declare A Recordset ?
Hi allHow do i declare a recordset and fetch records from an sql server?TIAGuy

View Replies !
Declare @var Text
Hi,

I want to store more than 8000 characters. Ideally it might have been fine if decalre @var text had worked for me.

Can anyone tell is it possible....

thanks,
sajai.

View Replies !
DECLARE CURSOR
Is there any way to create a cursor, based on a dynamically created select_statement? Something like:
DECLARE someCRS CURSOR LOCAL FAST_FORWARD FOR @strSelect
where @strSelect is previously declared as let's say varchar.
I don't want to create a stored procedure for this.


Thanks!

View Replies !
Declare Variable For All In SP
In a previous life, for each variable that we passed into a query, we would set -1 to the default for all so that when we converted it to an SP, we could query a specific dataset or or all.  The following is a sample bit of code, I can not for the life of me remember how to pull back all using -1.

The following is the code that I currently have, it's a simplified version of the total SP that I am trying to use, but enough to give you the idea of what I am trying to do.

The MemberId field is a varchar(20) in the table.

Create procedure sp_GetClaims_BY_MemberID
@Memberid varchar (50)
as
Select top 100 * from [QICC-TEST].dbo.tblClaims_eligible
where Membid = @memberid

EXEC sp_GetClaims_BY_MemberID '99999999999'

The above SP works fine, I just need to be able to modify it so that I can pull back all records for all member id's, any suggestions?

 I am currently working in SQL 2000.

View Replies !
Help With Declare And Cursor
 

I keep getting the message

Msg 156, Level 15, State 1, Line 3

Incorrect syntax near the keyword 'declare'.

Msg 156, Level 15, State 1, Line 4

Incorrect syntax near the keyword 'declare'.

 

What am I doing wrong?

 

 

declare @dbname varchar(8000),

declare @countyname varchar (200) ,

declare @sql varchar(8000)

 

declare county_name cursor for

select distinct county from Zipcodes

open county_name

fetch next from county_name

into @countyname

 

declare dbname_name cursor for

select name from sys.databases where name like 'Property%' and name <> 'PropertyCenter'

open dbname_name

fetch next from dbname_name

into @dbname

 

 

WHILE @@FETCH_STATUS = 0

BEGIN

set @sql =

'

select p.sa_property_id, z.zipcode as sa_site_zip, z.state as sa_site_state, z.city as sa_site_city, z.county as sa_site_county,@dbname ,(select @@servername) as servername, county'+@countyname+'

from zipcodes z join tbl_reply_assr_final p on z.zipcode = p.sa_site_zip'

exec (@sql)

end

set @sql = ''

fetch next from dbname_name into @dbname

fetch next from county_name into @countyname

 

 

CLOSE county_name

DEALLOCATE county_name

CLOSE dbname_name

DEALLOCATE dbname_name

View Replies !
Declare Variable
Declare @DBName varchar(25)
select @DBName = 'Production'
Select @DBName = @DBName + '.dbo.'+'sysfiles'
select @DBName
select * from @DBName
 
When I executes above lines of code in query analyser it give me an error like :
 
Server: Msg 137, Level 15, State 2, Line 5
Must declare the variable '@DBName'.
 
give me solution as soon as possible
 
Thanks
Aric

View Replies !
Why Declare Does Not Work
declare @fdas as varchar(10)
set @fdas = 'master'

use @fdas

i try to execute this one it does not work
said that Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '@fdas'. how to fix that one? by not replacing the @fdas

but i got master database

------------

what is the difference actually between

use master than the first querry?



arifliminto86

View Replies !
Declare Table
Dear All,
actually, in our application, we are using so many temporary local variables like @table_name....

and based on these local variables, we are making joins with the regular adtabase tables. is it better thing instead of temp tables?

what exactly i want to know is,
@table_name,#temp_table,##temp_table.....
in these three processes, which one is the best one...

thanks in advance

Vinod
Even you learn 1%, Learn it with 100% confidence.

View Replies !
Declare Table
When I run this script.It gives me an error that I need to "Delcare @pc2" Why? Please help.

Declare @pc2 Table

([prop_char_typ_code] [varchar](5) NOT NULL,
[tax_year] [varchar](4) NOT NULL,
[property_id] [int] NOT NULL,
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [varchar](100) NULL,
[prop_segment_id] [int] NULL)

Insert into @pc2

([prop_char_typ_code],
[tax_year],
[property_id],
[id],
[value],
[prop_segment_id])

Select

[prop_char_typ_code],
[tax_year],
[property_id],
[id],
[value],
[prop_segment_id]

from property_char


Go

SELECT 'ACRES', '2008', property_char.property_id, ROUND(property_char.value,0)
FROM

property_char INNER JOIN
property ON property_char.property_id = property.id INNER JOIN
property_char AS @pc2 ON property.id = @pc2.property_id INNER JOIN
prop_valuation ON property.id = prop_valuation.property_id INNER JOIN
val_component ON property.id = val_component.property_id

WHERE property_char.property_id < 81695 AND
property_char.property_id = property.id AND
property_char.prop_char_typ_code = 'SIZE' AND
property_char.tax_year = '2008' AND
@pc2.prop_char_typ_code = 'USECD' AND
(@pc2.value not in ('85','86','87','88','95') AND --( <=== Review list of Usecodes))
@pc2.tax_year = '2008' AND
@pc2.property_id = property.id AND
property.pact_code = 'REAL' AND
(property.eff_to_date is null OR property.eff_to_date >= getdate())AND
prop_valuation.property_id = property.id AND
prop_valuation.tax_year = '2008' AND
prop_valuation.local_assed_ind = 'Y' AND
val_component.value_type = 'MKLND' AND
val_component.property_id = property.id AND
val_component.tax_year = '2008' AND
val_component.modified_value > 0)AND
NOT EXISTS (Select 'z' from parcel_exclude where property.parcel_number = parcel_exclude.parcel_number AND special_assessment = 'CD')

View Replies !
Declare A Concatenated Value.
OMG i'm so stupid, i edited my original post instead of replying!!

I was wondering if there was away to write a stored procedure where I concatenate several columns to create a Phrase and use that Phrase as a new value to do a second search in another table.

Example.

Table 1.

Column1 (Modem) Column2 (Highspeed) Column3 (Black)

Concatenated to be MODEM HIGHSPEED BLACK.

The 2nd table has the concatenated value as it's own column and 2nd column for the number in Inventory.

Column1 (MODEM HIGHSPEED BLACK) Column2 (44)

View Replies !
Must Declare The Scalar Variable
Hi with the code below I am getting the error
Error inserting record. Must declare the scalar variable "@contractWHERE"
 I removed @contract and it then gave me the error
Error inserting record. Must declare the scalar variable "@zipWHERE"
 I was wondering if some can point me in the right direction for fixxing this
protected void cmdUpDate_Click(Object sender, EventArgs e)
{
//Define ADO.NET Objects.
string updateSQL;
updateSQL = "UPDATE Authors SET ";
updateSQL += "au_id=@au_id, au_fname=@au_fname, au_lname=@au_lname, ";
updateSQL += "phone=@phone, address=@address, city=@city,state=@state, ";
updateSQL += "zip=@zip, contract=@contract";
updateSQL += "WHERE au_id@au_id_original";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(updateSQL, con);
//Add the parameters.
cmd.Parameters.AddWithValue("@au_id", txtID.Text);
cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text);
cmd.Parameters.AddWithValue("@au_lname", txtLastName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@city", txtCity.Text);
cmd.Parameters.AddWithValue("@state", txtState.Text);
cmd.Parameters.AddWithValue("@zip", txtZip.Text);
cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));
cmd.Parameters.AddWithValue("au_id_original", lstAuthor.SelectedItem.Value);
//Try to open the database and execute the update
try
{
con.Open();
int updated = cmd.ExecuteNonQuery();
lblStatus.Text = updated.ToString() + " records inserted.";
}
catch (Exception err)
{
lblStatus.Text = "Error inserting record. ";
lblStatus.Text += err.Message;
}
finally
{
con.Close();
}
}
}
 
Many Thanks in advance
 

View Replies !
Must Declare The Scalar Variable
I'm making an ecommerce web app from following the Apress "Beginning ASP.Net 2 E-commerce with C#" book, and when I implement a stored procedure (I made a mdf DB in the app_Data folder), I get the following message: Must declare the scalar variable @CategoryIDThe code used to obtain this error is below: CREATE PROCEDURE DeleteCategory(@CategoryINT int)ASDELETE FROM CategoryWHERE CategoryID = @CategoryID I get this error with every Stored Procedure I try to implement. What should I do to fix this? In SQL Server 2k5 Management Studio, this problem does not present itself.

View Replies !
How To Declare Global Sqlcommands...
Hello guys! Is it possible to declare global sql commands and call it in a rowcommand_function?
Here's what I did...
  Dim p_s_syounin2 As New SqlCommand
Dim cnn As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("StrConn").ConnectionString)

Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)

If (Session("syozokubu_id") = 20) And (Session("syozokuka_id") = 21) And ((Session("kaikyuu_id") = 23)) Then

p_s_syounin2.CommandText= ("UPDATE TE_shounin_zangyou SET p_s_syounin2=syain_hnm FROM TR_syainID WHERE syozokubu_id=20 AND syozokuka_id=21 AND kaikyuu_id=23")
'''' connection string is not placed here acc. to my research
End If

End Sub

Protected Sub my_gridview_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles my_gridview.RowCommand



If e.CommandName = "Approve" Then

cnn.Open()
p_s_syounin2.ExecuteNonQuery()

cnn.Close()

End If

End Sub




 
I get an error message that says " ExecuteNonQuery: Connection property has not been initialized. " 
 
Please help me.
 
Thanks guys.
 
Audrey

View Replies !
Must Declare The Scalar Variable
Hello!

I have a aspx page in which I have a Gidview populated by a sqlDataSouce.
This is my code:



<%@ Page Language="VB" AutoEventWireup="false" CodeFile="CostEmployee1.aspx.vb" Inherits="RecursosHumanos_CostEmployee1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Style="z-index: 100; left: 0px; position: absolute; top: 0px"> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <Columns> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="Editar" Text="Editar" runat="server" CommandName="Edit"></asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Actualizar" style="color: white"></asp:LinkButton> <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancelar" style="color: white"></asp:LinkButton> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="Apagar" Text="Apagar" runat="server" CommandName="Delete" OnClientClick='return confirm("Tem a certeza que deseja apagar este registo?");' CausesValidation="false"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Id_CostEmployee" InsertVisible="False" SortExpression="Id_CostEmployee"> <EditItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Eval("Id_CostEmployee") %>'></asp:Label> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("Id_CostEmployee") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Id_Employee" SortExpression="Id_Employee"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Id_Employee") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("Id_Employee") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="FullName" SortExpression="FullName"> <EditItemTemplate> <asp:TextBox ID="textbox5" runat="server" Text='<%# Bind("FullName")%>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label6" runat="server" Text='<%# Bind("FullName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="NumEmployee" SortExpression="NumEmployee"> <EditItemTemplate> <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("NumEmployee") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label7" runat="server" Text='<%# Bind("NumEmployee") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Period" SortExpression="Period"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Period") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("Period") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="CostHour" SortExpression="CostHour"> <EditItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("CostHour") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label4" runat="server" Text='<%# Bind("CostHour") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Date" SortExpression="Date"> <EditItemTemplate> <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Date") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label5" runat="server" Text='<%# Bind("Date") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> <RowStyle BackColor="#EFF3FB" /> <EditRowStyle BackColor="#2461BF" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EuroscutConnectionString %>" SelectCommand="SELECT [HR.CostEmployee].Id_CostEmployee, [HR.CostEmployee].Id_Employee, [HR.CostEmployee].Period, [HR.CostEmployee].CostHour, [HR.CostEmployee].Date, [HR.Employee].FullName, [HR.Employee].NumEmployee FROM [HR.CostEmployee] INNER JOIN [HR.Employee] ON [HR.CostEmployee].Id_Employee = [HR.Employee].Id_Employee"
UpdateCommand="UPDATE [HR.CostEmployee] set Period = @Period, CostHour = @CostHour where Id_CostEmployee = @Id_CostEmployee"
DeleteCommand="DELETE from [HR.CostEmployee] where (Id_CostEmployee = @Id_CostEmployee)"> <UpdateParameters> <asp:Parameter Name="Period" /> <asp:Parameter Name="CostHour" /> <asp:Parameter Name="Id_CostEmployee" /> </UpdateParameters> <DeleteParameters> <asp:Parameter Name="Id_CostEmployee" Type="int32" /> </DeleteParameters> </asp:SqlDataSource> </div> </form></body></html> When I run the page I'm able to edit the row but when I try to delete it gives me the error:

Must declare the scalar variable "@Id_CostEmployee".

I'm tired of "googling" this error, and I've tried all the advices, nothing...
I don't know what is happening here, I have 5 other forms, all simillar and they all work!

Any suggestions, pleeeeaaaase?

Thank's!
Paula

View Replies !
Must Declare The Scalar Variable
Hi,
I found a nice tutorial on the net on how storing images to a SQL DB (http://blogs.msdn.com/jdixon/articles/495408.aspx) but have some troubles in retreiving the image back from the database.
Once I click the View details link, I receive an error message "Must declare the scalar variable @..."
Can someone tell me how I can define this scalar variable and/or how I can display an image from my database ?
Thanks to all !!!
Bart

View Replies !
Declare Variable Dynamically
I'm attempting to modify some Crosstab generating code, and I need someadvice/examples.Currently, the code uses a single string variable to store thedynamically generated query (www.johnmacintyre.ca). The problem is thatI am trying to pivot biological taxonomy information, and may end upwith a table containing over 200 columns. This takes the dynamic stringwell over the 8000char limit for variables.[color=blue]>From my understanding, the EXEC() command does not have the 8000char[/color]limit if the execution string is broken into chunks, and concatenatede.g. EXEC(sql1 + sql2 + sql3 + ...). So the solution I think I need isto:1) start a counter at the beginining of the dynamic generation2) append the counter value to the end of a string variable name3) DECLARE the new variable and attach that loop cycle of text to it,or attach each chunk of characters < 80004) build the EXEC() string by concatenating each dynamic varibleCan this be done? Should it be done? Is there a better way to addressthis type of problem?Thanks for any ideas or insightsTim Pascoe

View Replies !
Need To Declare Multiple Values
Alright, so I have this problem. I want to make it easy for me andothers to be able to run a query and easily choose whether we wantMerchants or NonMerchants. Previously, we would have to comment outbits of code and would leave things messy (it would also leave room forerror). So, I'm thought DECLARE and SET would work. Wrong.This is what I have....DECLARE @Merchant VARCHARSET @Merchant = (Select CONVERT(VARCHAR, Id) + ','FROM AdminAdvertiserTypesDDLWHERE Id IN (1,3,4,5)) // Includes Active, Out of Business, Cease to do business, InactiveI've also tried...SET @Merchant = '1,3,4,5'Then, in the query itself I try:WHERE AdminAdvertiserTypesDDL.Id = @MerchantorWHERE AdminAdvertiserTypesDDL.Id IN @MerchantorWHERE AdminAdvertiserTypesDDL.Id IN (@Merchant)orWHERE AdminAdvertiserTypesDDL.Id LIKE @MerchantEither way, it will ONLY show me the merchants whose Id is 1. When Imake the query:WHERE AdminAdvertiserTypesDDL.Id IN (1,3,4,5)I finally get the desired results.Any ideas or tips?Thank you so much!

View Replies !
Declare An Array Of Int In SQL Server
Hi All,I want declare an array of int in SQL Serverplease help me to convert the following code from VB to TSQL------------Dim md_mon(12) As Integermd_mon(1) = 31-------------Thanks

View Replies !
Declare Or Create Cursor
Hello guys,just wanted to ask a question some might percieve it as a stupid one but I don't know so I will ask anyway?

Is Declare Cursor same as Create Cursor and if not what is the major difference?

View Replies !
Declare Cursor With Dynamic SQL?
Hello..

Can you declare a cursor with dynamic SQL?

I have a situation where the SQL for my cursor MUST be assembled in a buffer, but I cannot get the cursor declaration to accept my buffer as the SQL statement.

these attempts did not work:

DECLARE crsCursor CURSOR FOR @vchrSQL
DECLARE crsCursor CURSOR FOR (@vchrSQL)

Does anybody know if you definitely can or definitely cannot use dynamic SQL with cursors?

View Replies !
SELECT DISTINCT In DECLARE
Hi


I try to use this code in query analyzer

DECLARE @SendTo VarChar(4000)
SET @SendTo = ''
SELECT DISTINCT @SendTo = @SendTo + UserEmail + ';' FROM dbo.tbl_AccountInfo WHERE (UserEmail <> '')
PRINT @SendTo

The purpose of this code is to build up a ; seperated string of email adresses that I can use sending mail from SQL server.

It works but it only give me one record (should give me 130 records) , but if I remove the DISTINCT part it give me all records, duplicates too. Does anyone know why and how can I get this to work? Or maybe do it in another way?


Best regards

View Replies !
How Long Declare @ Can Hold On?
Currently i have a long long query may run 10 hours
but i wonder if i declare :
DECLARE @rows int

how long it will hold on its value??

View Replies !
Is There A Way To Declare Constant Variables ?
Or, is the only way to use "declare" and "set" only ?

View Replies !
How Can I Create View Within Declare ?
 

dear all

how can i create view within declare ?

if i had one script contains declare if it is possible to combine both table with union ?

declare @a varchar(20)
select @a = ptraceno from phonelevel
where(ptraceno = '0913787170' or otherno = '0913787170')
select * from phonelevel where ptraceno = @a

declare @b varchar(20)
select @b = ptraceno from phonelevel
where(ptraceno = '0913011676' or otherno = '0913011676')
select * from phonelevel where ptraceno = @b

View Replies !
Must Declare The Scalar Variable
 

create PROCEDURE [Update_Purged]



AS

Declare @Stg_Purged_union table

(PurgedAccountUnionID int IDENTITY,

Coid char(50),

FacilityId int,

AccountID int,

PatientName char(50),

PatientNo char(50),

PT char(50),

ST char(50),

PurgeDt datetime);

BEGIN

INSERT INTO @Stg_Purged_Union

([Coid]
,null
,null

,[PatientName]

,[PatientNo]

,[PT]

,

,[PurgeDt])

select coid, patientname, patientno, pt, st, purgedt from

[Stg_PurgedAccount]
 

--updating the facilityid in @stg_purged_account_file_union
 

update @stg_purged_union set facilityid=(select

facilityid from appfacility as b

where b.unitnum=(select

unitnum from appfacility as c

where c.unitnum=b.unitnum) and @Stg_Purged_Union.coid=b.unitnum)

 
 
I am getting the following error.

Must declare the scalar variable "@Stg_Purged_Union"

View Replies !
Declare Variables In A SP Dynamic?
Hello there,
 
i have been asked about a thing that, i think, is not possible. But maybe i am wrong.
 
question:
Is it possible to have a Stored Procedure in that the declaration of the variables is dynamic?
This means, can i get the variable name and the type of it from a database to create
a dynamic stored procedure that changes itself by firing a trigger.
 
Thanks for all oppinions and answers.
everWantedLINUX

View Replies !
Declare Variable Error
Can anyone tell me why I keep getting this error? I am declaring the variable, but it's not recognizing it? What am I missing?

------error---------------
Server: Msg 137, Level 15, State 2, Procedure sp_CopyData, Line 85
Must declare the variable '@DatabaseFrom'.

-----sp----

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


create Procedure dbo.sp_CopyData
(@ClientAbbrev nchar(4) )
AS
DECLARE @DatabaseFrom varchar(100)

Set @DatabaseFrom = @ClientAbbrev + '.dbo.tsn_ClaimStatus'

--------------------------------------------------------------
delete from sherrisplayground.dbo.tsn_ClaimStatus
where csclientcode = @ClientAbbrev


---Insert Data from Original table into copied table---------
Insert into [AO3AO3].sherrisplayground.dbo.tsn_ClaimStatus (
CsClientCode,
ClaimStatusID,
Pat,
Claim,
[ID],
Code,
[Date],
ActionID,
Comment2,
Comment3,
Comment4,
[Followup Date],
Checkamt,
UserName)
select
@ClientAbbrev,
ClaimStatusID,
Pat,
Claim,
[ID],
Code,
[Date],
ActionID,
Comment2,
Comment3,
Comment4,
[Followup Date],
Checkamt,
UserName
from @DatabaseFrom


return


GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

View Replies !
Using A Variable In SQL Script (Declare @x)
I am not sure why the following does not work...

I am declaring a variable to hold a string to be used in my script. The contents of the variable looks perfect and works independently, the variable it does not work. (BTW, do you call this a variable in T-SQL too?). The idea is to pass the value to the script to generate different results sets.

//Parameter
DECLARE @Codes varchar(8000);
SET @Codes = '''07-1110_CHA,1'',''07-1110_DCV,2''';

//Examine contents - results: '07-1110_CHA,1','07-1110_DCV,2'
Select @Codes;

//Works fine
Select screening_cd,check_amount
From accounting
Where screening_cd in ('07-1110_CHA,1','07-1110_DCV,2');

//This does not work
Select screening_cd,check_amount
From accounting
Where screening_cd in (@Codes);

TIA

View Replies !
Error 137: Must Declare Variable ...
Hello,

I have the following SP, which gives out a "Error 137: Must declare variable @tmp_return_tbl" error.

This is the important part of the code:
.
.
.
-- DECLARE TABLE VARIABLE
DECLARE @tmp_return_tbl TABLE (tID int, Text_Title nvarchar(30), Text_Body nvarchar(100))

-- fill out table variable USING A SELECT FROM ANOTHER TABLE VARIABLE
-- NO PROBLEM HERE
INSERT INTO @tmp_return_tbl
SELECT TOP 1 * FROM @tmp_tbl
ORDER BY NEWID()

-- TRYING TO UPDATE A TABLE
UPDATE xTable
SET xTable.fieldY = xTable.fieldY + 1
WHERE xTable.tID = @tmp_return_tbl.tID --THIS PRODUCES THE ERROR
.
.
.

I know I cannot use a table variable in a JOIN without using an Alias, or use it directly in dynamic SQL (different scope) - but is this the problem here? What am I doing wrong?

Your help is much appreciated.

View Replies !
Declare Un-static Decimal Value
I try to declare a variable with un static decimal point in the following statement:-

declare @mpt int;
declare @mpq nvarchar (1)
SELECT @mpq = (SELECT mpq FROM ims.parm)

exec('declare @MM1 decimal (10,'+ @mpq +');')

set @mm1 = 1
print @mpt
when i print the declare statement looks like the following:
declare @MM1 decimal (10,2);
but with exec the statement, I have the following error:-
Msg 137, Level 15, State 1, Line 18
Must declare the scalar variable "@mm1".

Best regards

View Replies !
Must Declare Scalar Variable @ID
the following is my code
can anybody rectify my problem that i get when running my application
"Must declare scalar variable @ID"
<asp:GridView ID="GridView1" DataKeyNames="ID" runat="server" AutoGenerateColumns="False" BackImageUrl="~/App_Themes/SkinFile/back1.jpg"
BorderColor="Teal" BorderStyle="Solid" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ButtonType="Button" ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="Answers" HeaderText="Answers" SortExpression="Answers" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:YahooConnectionString7 %>"
DeleteCommand="DELETE FROM Answers WHERE (ID = @ID)" InsertCommand="INSERT INTO Answers(ID, Answers) VALUES (@ID, @Answers)"
SelectCommand="SELECT Answers.* FROM Answers" UpdateCommand="UPDATE Answers SET ID = @ID, Answers = @Answers WHERE (ID = @ID)">
<DeleteParameters>
<asp:Parameter Name="ID" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="ID" />
<asp:Parameter Name="Answers" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="ID" />
<asp:Parameter Name="Answers" />
</InsertParameters>
</asp:SqlDataSource>

View Replies !
How Should We Declare Long Numbers
when dealing with long numbers in appllications like: 1000000000 up to 9999999999999
in what type is it better to declare them (varchar, bigint.....)
Thanks

View Replies !
Must Declare Scalar Variable???
OK i have my stored procedure all set up and working.. But when i try and add a second variable called @iuser and then after i execute the stored procedure, i get an error saying:-
ERROR
"Must declare scalar variable @iuser"

Here is the code i am using in my stored proc, also my stored proc worked fine before i used a second variable??!

//BEGIN

ALTER PROCEDURE [dbo].[putpending]
(@cuuser nvarchar(1000), @iuser nvarchar(1000))

AS
Declare @sql nvarchar(1000)

SELECT @sql =
'INSERT INTO ' +
@cuuser +
' (Pending) VALUES (@iuser)'

EXECUTE (@sql)

RETURN
//END

And i know my VB.NET code is working but i will put it in anyway:-

//BEGIN

'variables
Dim user As String
user = Profile.UserName
Dim intenduser As String
intenduser = DetailsView1.Rows(0).Cells(1).Text.ToString()

'connection settings
Dim cs As String
cs = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|friends.mdf;Integrated Security=True;User Instance=True"
Dim scn As New SqlConnection(cs)
'parameters
Dim cmd As New SqlCommand("putpending", scn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@cuuser", SqlDbType.NVarChar, 1000)
cmd.Parameters("@cuuser").Value = user
cmd.Parameters.Add("@iuser", SqlDbType.NVarChar, 1000)
cmd.Parameters("@iuser").Value = intenduser
'execute
scn.Open()

cmd.ExecuteNonQuery()

scn.Close()
//END

Any ideas why i am getting this error message?

View Replies !
Must Declare The Scalar Variable
Following stored proc uses dynamic sql but it gives the error
Msg 137, Level 15, State 2, Line 3
Must declare the scalar variable "@ProjectBenefitID".
though its declared .please. tell the workaround



ALTER PROCEDURE [dbo].[spPMPT_GetBenefit]

@ProjectBenefitID INT,

@OrderBYVARCHAR(40),
-- Parmeters for Paging [Start]
@TotalPages INT OUT ,
@CurrentPageNumber INT OUT ,
@NumberOfRecordsINT = 5, /*PageSize*/
@CurrentPage INT = 0/*PageNumber*/

-- Parmeters for Paging [End]

AS

SET NOCOUNT ON

DECLARE @TMPFLOAT
DECLARE @ErrorMsgID INT
DECLARE@ErrorMsg VARCHAR(200)


----- Paging declarations start
DECLARE @SQLFinal NVARCHAR(4000)
DECLARE @Count INT
DECLARE @SC VARCHAR(4000)
----- Paging declarations end


DECLARE@SelectASVARCHAR(4000)
DECLARE@FromASVARCHAR(4000)
DECLARE@WhereASVARCHAR(4000)
DECLARE@LsOrderBy ASVARCHAR(4000)



-- Initialize vars
SET @SC= ''
SET @From= ''
SET @Where= ''
SET @Select= ''
SET @SQLFinal= ''
SET @Count= 0


IF (@CurrentPage = 0 OR @CurrentPage IS NULL)
BEGIN
--Generate error message
SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. The Page Number cannot be zero.'
--Raise error to the user
RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/)
--Return error indicator
RETURN (-1)
END
IF (@NumberOfRecords = 0 OR @NumberOfRecords IS NULL )
BEGIN
--Generate error message
SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. Number of records per page cannot be zero.'
--Raise error to the user
RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/)
--Return error indicator
RETURN (-1)
END
IF (@Orderby IS NULL OR @Orderby = '')
BEGIN
--Generate error message
SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. The Order by cannot be null.'
--Raise error to the user
RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/)
--Return error indicator
RETURN (-1)
END




CREATE TABLE #TEMP_BENEFIT1
(

AssessBenefitID INT,
ProjectBenefitID INT,
ExpectedQuantity INT,
ExpectedQuality VARCHAR(2000),
Comments VARCHAR(2000)
)

INSERT INTO #TEMP_BENEFIT1 SELECT AssessBenefitID,ProjectBenefitID,
Quantity,Quality,
Comments
FROM PMPT_AssessBenefit
WHERE ProjectBenefitID=@ProjectBenefitID AND AssessFlag='E' --and AssessBenefitID=@IterationID

CREATE TABLE #TEMP_BENEFIT2
(

AssessBenefitID INT,
ProjectBenefitID INT,
ActualQuantity INT,
QtyFileID INT,
QtyFileName VARCHAR(100),
QtyFilepath VARCHAR(100),
ActualQuality VARCHAR(2000),
QuaFileID INT,
QualFileName VARCHAR(100),
QualFilepath VARCHAR(100),
Comments VARCHAR(2000),
refAssessBenefitID INT,
DateasON DATETIME
)

INSERT INTO #TEMP_BENEFIT2 SELECT PAB.AssessBenefitID,PAB.ProjectBenefitID,
PAB.Quantity,pab.qtyFileID,
(SELECT FileName FROM PMPT_Files WHERE FileID = pab.qtyFileID) as QtyFileName,
(SELECT UploadedFilePath FROM PMPT_Files WHERE FileID = pab.qtyFileID) as QtyFilepath,
PAB.Quality,pab.quaFileID,
(SELECT FileName FROM PMPT_Files WHERE FileID = pab.quaFileID) AS QualFileName,
(SELECT UploadedFilePath FROM PMPT_Files WHERE FileID = pab.quaFileID) as QuaFilepath,
PAB.Comments,PAB.refEXPAssessBenefitID,PAB.DateasON
FROM PMPT_AssessBenefit PAB
WHERE ProjectBenefitID=@ProjectBenefitID AND AssessFlag='A'


DECLARE @UNIT VARCHAR(100)
SELECT @UNIT=NAME FROM PMPT_Picklists WHERE PicklistID = (SELECT unitID FROM PMPT_ProjectBenefits WHERE ProjectBenefitID=@ProjectBenefitID)

IF @UNIT IS NULL
SET @UNIT = ''
SET @Select='
DECLARE @UNIT VARCHAR(100)
SELECT @UNIT=NAME FROM PMPT_Picklists WHERE PicklistID = (SELECT unitID FROM PMPT_ProjectBenefits WHERE ProjectBenefitID='+CONVERT(VARCHAR(10),@ProjectBenefitID))+'
SELECTT1.AssessBenefitID, CAST(T1.ExpectedQuantity AS VARCHAR)+'' ''+ @UNIT as ExpectedQuantity,
CAST( T2.ActualQuantity AS VARCHAR)+'' ''+ @UNIT as ActualQuantity, T2.QtyFileID, T2.QtyFileName AS QtyFileName ,T2.QtyFilepath, T1.ExpectedQuality AS ExpectedQuality , T2.ActualQuality AS ActualQuality ,
T2.QuaFileID,T2.QualFileName AS QualFileName ,T2.QualFilepath, T2.COMMENTS,CONVERT(VARCHAR(10),T2.DateasON,103) AS DateasON
FROM#TEMP_BENEFIT1 T1,#TEMP_BENEFIT2 T2
WHERET1.AssessBenefitID = T2.refAssessBenefitID'

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved