Showing posts with label field. Show all posts
Showing posts with label field. Show all posts

Thursday, March 29, 2012

DataType Issue

Hi

Using SQLserver 2000 I have to enter a huge data (nearly 8000 charcters) into a field, which data type is suitable for that and what is the method to store data.

You might need to use a VARCHAR(8000) or a text datatype; however, there is not enough information.

Is your data divisible into different definite pieces? Do you need to support unicode? Is your data numeric? binary? Is your data XML Is there additional data that needs to be stored with the 8000 characters?

DataType change

I recieve a text file with a field that has a text format of 20010910. I import this data into sql server 7.0 utilizing the import wizard. (The wizard will not convert the data to datetime format) I need to know how to convert this data into date format of 2001/09/10. How do I do this in sql.

Thank You,
David A. FullertonYou can add a string column to your table and CONVERT in a post-importing execution or use Visual Basic CDATE in Transformation tab in DTS just before click OK in usual IMPORT... dialog|||CDATE will not work in this example. However, I agree with Cesar's recommendations. In this case, since using vbscript will be more complicated than using cdate you can try the following after the data is loaded:

select convert(varchar(10), cast('20010920' as datetime), 111)|||Thank You That worked..Have a great day!|||Happy to help and good luck.

Tuesday, March 27, 2012

Datatime order by Problem

Hi everybody,
I have onde table called (TB) with two fields : F1(int) and F2(varchar:10)
In this table the field F2 is used to store dates in the format
dd/mm/yyyy (27/12/2002). Its is record as varchar and undesired.
I need to select all records from a single id from the field F1 and
then order by the result set by date to result set be this way:

F1 F2
------------
01 15/12/1975
01 15/12/1980
01 16/12/1998
01 27/12/2003
------------

To do this Im using the follow syntax :

SELECT * FROM TB
WHERE (F1 = '01')
ORDER BY CAST(F2 AS datetime(103))

But it gives the follow message erro trying to select data :

[Microsoft][ODBC SQL Server Driver][SQL Server]The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

How can I convert the format used in the select to order by date type in a SQL Server range datetype to get a result set as above?

Thansk for attention.

Leonardo AlmeidaUse convert(datetime, f2, 103) instead of the cast.sql

Sunday, March 25, 2012

Datasets in same region ?

Is it possible to use different datasets in the same region in the report.
Let's say I have 2 sources which I need to combine, I have a field in each
source I need to add together and see that result for a list of different
accounts.
I tried to do it in an expression choosing the datasets, It works with sums
but how to make it work with the single field and not the total ?
I get this error
g:\surround\reportingservice\axapta\test flere kilder\FlereKilder.rdl The
value expression for the textbox 'textbox12' contains an error: [BC30198]
')' expected.
Here is the Expression
= (Fields!VAREBELXB.Value, "DataSet1") + (Fields!VAREBELXB.Value, "C5_300")
Thx
JackNo, you can only get aggregated values from the other dataset that is not
bound to the region. I would gravitate toward doing the merging at the data
source.
--
HTH,
---
Teo Lachev, MVP, MCSD, MCT
"Microsoft Reporting Services in Action"
"Applied Microsoft Analysis Services 2005"
Home page and blog: http://www.prologika.com/
---
"Jack" <jackdSPAM@.jackd.dk> wrote in message
news:%2372mERr6FHA.636@.TK2MSFTNGP10.phx.gbl...
> Is it possible to use different datasets in the same region in the report.
> Let's say I have 2 sources which I need to combine, I have a field in each
> source I need to add together and see that result for a list of different
> accounts.
> I tried to do it in an expression choosing the datasets, It works with
> sums but how to make it work with the single field and not the total ?
> I get this error
> g:\surround\reportingservice\axapta\test flere kilder\FlereKilder.rdl The
> value expression for the textbox 'textbox12' contains an error: [BC30198]
> ')' expected.
> Here is the Expression
> = (Fields!VAREBELXB.Value, "DataSet1") + (Fields!VAREBELXB.Value,
> "C5_300")
>
> Thx
> Jack
>|||The problem is that it is from two different sources, one informix database
and one SQL database :(|||What a good reason to use SQL Server 2005 CLR stored procedures :-) Worse
come worse, I would combine the datasets at a application level and pass the
resulting ADO.NET dataset to the report using a custom data extension.
--
HTH,
---
Teo Lachev, MVP, MCSD, MCT
"Microsoft Reporting Services in Action"
"Applied Microsoft Analysis Services 2005"
Home page and blog: http://www.prologika.com/
---
"Jack" <jackdSPAM@.jackd.dk> wrote in message
news:O1$gLS26FHA.2628@.TK2MSFTNGP11.phx.gbl...
> The problem is that it is from two different sources, one informix
> database and one SQL database :(
>|||One of my colleagues thinks it's possible to make the solution in vb code,
but I don't know how to get the right data from the second dataset. There
has to be som filtering to get the right data to add, but I have no clue how
to do it in vb code.
Jack
"Teo Lachev [MVP]" <teo.lachev@.nospam.prologika.com> skrev i en meddelelse
news:uIM7$e36FHA.472@.TK2MSFTNGP15.phx.gbl...
> What a good reason to use SQL Server 2005 CLR stored procedures :-) Worse
> come worse, I would combine the datasets at a application level and pass
> the resulting ADO.NET dataset to the report using a custom data extension.
> --
> HTH,
> ---
> Teo Lachev, MVP, MCSD, MCT
> "Microsoft Reporting Services in Action"
> "Applied Microsoft Analysis Services 2005"
> Home page and blog: http://www.prologika.com/
> ---
> "Jack" <jackdSPAM@.jackd.dk> wrote in message
> news:O1$gLS26FHA.2628@.TK2MSFTNGP11.phx.gbl...
>> The problem is that it is from two different sources, one informix
>> database and one SQL database :(
>>
>|||I can see the idea of making a combined dataset in a dll with c sharp or
something, but how do I get this dataset into reporting services to use on
the layout tab ?
"Teo Lachev [MVP]" <teo.lachev@.nospam.prologika.com> skrev i en meddelelse
news:uIM7$e36FHA.472@.TK2MSFTNGP15.phx.gbl...
> What a good reason to use SQL Server 2005 CLR stored procedures :-) Worse
> come worse, I would combine the datasets at a application level and pass
> the resulting ADO.NET dataset to the report using a custom data extension.
> --
> HTH,
> ---
> Teo Lachev, MVP, MCSD, MCT
> "Microsoft Reporting Services in Action"
> "Applied Microsoft Analysis Services 2005"
> Home page and blog: http://www.prologika.com/
> ---
> "Jack" <jackdSPAM@.jackd.dk> wrote in message
> news:O1$gLS26FHA.2628@.TK2MSFTNGP11.phx.gbl...
>> The problem is that it is from two different sources, one informix
>> database and one SQL database :(
>>
>|||Another option is to link the Informix server as a linked server to your SQL
Server to submit a heterogeneous query (OPENQUERY or OPENROWSET).
--
HTH,
---
Teo Lachev, MVP, MCSD, MCT
"Microsoft Reporting Services in Action"
"Applied Microsoft Analysis Services 2005"
Home page and blog: http://www.prologika.com/
---
"Jack" <jackdSPAM@.jackd.dk> wrote in message
news:OZHpRjD7FHA.736@.TK2MSFTNGP09.phx.gbl...
> One of my colleagues thinks it's possible to make the solution in vb code,
> but I don't know how to get the right data from the second dataset. There
> has to be som filtering to get the right data to add, but I have no clue
> how to do it in vb code.
> Jack
> "Teo Lachev [MVP]" <teo.lachev@.nospam.prologika.com> skrev i en meddelelse
> news:uIM7$e36FHA.472@.TK2MSFTNGP15.phx.gbl...
>> What a good reason to use SQL Server 2005 CLR stored procedures :-) Worse
>> come worse, I would combine the datasets at a application level and pass
>> the resulting ADO.NET dataset to the report using a custom data
>> extension.
>> --
>> HTH,
>> ---
>> Teo Lachev, MVP, MCSD, MCT
>> "Microsoft Reporting Services in Action"
>> "Applied Microsoft Analysis Services 2005"
>> Home page and blog: http://www.prologika.com/
>> ---
>> "Jack" <jackdSPAM@.jackd.dk> wrote in message
>> news:O1$gLS26FHA.2628@.TK2MSFTNGP11.phx.gbl...
>> The problem is that it is from two different sources, one informix
>> database and one SQL database :(
>>
>>
>

Thursday, March 22, 2012

dataset query based on a global parameter

I need to create a report that displays data based on the userid. all the
records have a userid field filled with many userid values. how can I use the
global paramerer userid in the criteria for my dataset. so when a user run
the report olny records with his or her userid are showncreate a parameter with default value the global parameter. then use that
parameter in the query. ofcourse you can't use caching for those reports
"DJJIII" wrote:
> I need to create a report that displays data based on the userid. all the
> records have a userid field filled with many userid values. how can I use the
> global paramerer userid in the criteria for my dataset. so when a user run
> the report olny records with his or her userid are shown|||You do not have to have a 1:1 mapping between query parameters and report
parameters. Doing it the way suggested here means you have to muck around
with hiding it (since you don't want people to change it).
Have your query parameter, let's call it @.UserID. RS will automatically
recreate a report parameter called UserID but we won't use it. Click on the
..., go to parameters. Map the query parameter @.UserID to the global . The
parameter dialog box has a name and value columns. On the value side switch
it to expression. This brings you to the expression builder where you can
pick the User!UserID global variable. One thing to note, this variable has
the domain as well as the user id, so if you don't want this you will have
to strip it off.
Now, go you your layout, Report->Parameters and delete the now unneeded
UserID report parameter.
--
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"Antoon" <Antoon@.discussions.microsoft.com> wrote in message
news:04C477F1-17E5-47C5-BB11-9EF31278F1CE@.microsoft.com...
> create a parameter with default value the global parameter. then use that
> parameter in the query. ofcourse you can't use caching for those reports
> "DJJIII" wrote:
>> I need to create a report that displays data based on the userid. all
>> the
>> records have a userid field filled with many userid values. how can I use
>> the
>> global paramerer userid in the criteria for my dataset. so when a user
>> run
>> the report olny records with his or her userid are shown|||great tip, that is indeed a lot more practical
"Bruce L-C [MVP]" wrote:
> You do not have to have a 1:1 mapping between query parameters and report
> parameters. Doing it the way suggested here means you have to muck around
> with hiding it (since you don't want people to change it).
> Have your query parameter, let's call it @.UserID. RS will automatically
> recreate a report parameter called UserID but we won't use it. Click on the
> ..., go to parameters. Map the query parameter @.UserID to the global . The
> parameter dialog box has a name and value columns. On the value side switch
> it to expression. This brings you to the expression builder where you can
> pick the User!UserID global variable. One thing to note, this variable has
> the domain as well as the user id, so if you don't want this you will have
> to strip it off.
> Now, go you your layout, Report->Parameters and delete the now unneeded
> UserID report parameter.
> --
> Bruce Loehle-Conger
> MVP SQL Server Reporting Services
> "Antoon" <Antoon@.discussions.microsoft.com> wrote in message
> news:04C477F1-17E5-47C5-BB11-9EF31278F1CE@.microsoft.com...
> > create a parameter with default value the global parameter. then use that
> > parameter in the query. ofcourse you can't use caching for those reports
> >
> > "DJJIII" wrote:
> >
> >> I need to create a report that displays data based on the userid. all
> >> the
> >> records have a userid field filled with many userid values. how can I use
> >> the
> >> global paramerer userid in the criteria for my dataset. so when a user
> >> run
> >> the report olny records with his or her userid are shown
>
>

Wednesday, March 21, 2012

Dataset Field in Page/Table Header

Hi,
I want to print a field in the page header. Since there is no option in RS
to include a database field in Page Header, I placed the Field in a Table
header and set the the Repeat Header on Each Page Property. But it prints
the first value of the record on all page. Is it anyway to print the
database fields dynamically on the page header or table header.
TIA,
SamuelThe ReportItems!<ReportItemName>.Value syntax will allow you to do this. See
the sample report at the end of this posting. Also see the "Using Global
Collections" topic in SQL Server 2000 Reporting Services BOL (Books Online).
--
Bruce Johnson [MSFT]
Microsoft SQL Server Reporting Services
This posting is provided "AS IS" with no warranties, and confers no rights.
"Samuel" <samuel@.photoninfotech.com> wrote in message
news:ehqgckWdEHA.592@.TK2MSFTNGP11.phx.gbl...
> Hi,
> I want to print a field in the page header. Since there is no option in RS
> to include a database field in Page Header, I placed the Field in a Table
> header and set the the Repeat Header on Each Page Property. But it prints
> the first value of the record on all page. Is it anyway to print the
> database fields dynamically on the page header or table header.
> TIA,
> Samuel
>
ReportItemsSample.rdl
--
<?xml version="1.0" encoding="utf-8"?>
<Report
xmlns="http://schemas.microsoft.com/sqlserver/reporting/2003/10/reportdefini
tion"
xmlns:rd="">http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<PageHeader>
<ReportItems>
<Textbox Name="textbox2">
<Style>
<PaddingLeft>2pt</PaddingLeft>
<PaddingBottom>2pt</PaddingBottom>
<PaddingTop>2pt</PaddingTop>
<PaddingRight>2pt</PaddingRight>
</Style>
<Top>0.125in</Top>
<rd:DefaultName>textbox2</rd:DefaultName>
<Height>0.25in</Height>
<Width>1.75in</Width>
<CanGrow>true</CanGrow>
<Value>=ReportItems!textbox1.Value</Value>
<Left>0.25in</Left>
</Textbox>
</ReportItems>
<PrintOnLastPage>true</PrintOnLastPage>
<PrintOnFirstPage>true</PrintOnFirstPage>
<Style />
<Height>0.5in</Height>
</PageHeader>
<RightMargin>1in</RightMargin>
<Body>
<ReportItems>
<Textbox Name="textbox1">
<Style>
<PaddingLeft>2pt</PaddingLeft>
<PaddingBottom>2pt</PaddingBottom>
<PaddingTop>2pt</PaddingTop>
<PaddingRight>2pt</PaddingRight>
</Style>
<Top>0.25in</Top>
<rd:DefaultName>textbox1</rd:DefaultName>
<Height>0.25in</Height>
<Width>1.75in</Width>
<CanGrow>true</CanGrow>
<Value>Some Text in the Body. This could be a field reference (i.e.
=Fields!FieldName.Value)</Value>
<Left>0.25in</Left>
</Textbox>
</ReportItems>
<Style />
<Height>1.875in</Height>
</Body>
<TopMargin>1in</TopMargin>
<Width>6.50001in</Width>
<LeftMargin>1in</LeftMargin>
<rd:SnapToGrid>true</rd:SnapToGrid>
<rd:DrawGrid>true</rd:DrawGrid>
<rd:ReportID>d14a8b9b-cb8d-481b-8351-98a44abce6d7</rd:ReportID>
<BottomMargin>1in</BottomMargin>
<Language>en-US</Language>
</Report>

Monday, March 19, 2012

DataReader returns different results when there are null fields

If I query sql server I get 10 results. But when I use if (myReader.Read()) I get only 7 results. I found that there was a Null field in the DB. I changed it and it worked.
The problem is I don't want to touch the database and set all null fields. There must be a way to get all results including the Null using sqlDataReader so that if (myReader.Read()) is used it does the right comparison.

// This code is called 10 times with a select * from where item="xxx"
P21Conn.Open();

SqlDataReader myReader = cmd.ExecuteReader();

if (myReader.Read()) {

thanks
Rodin your select or sproc, use ISNULL or COALESCE around the columns that have null values.

cs|||Thank you

I did that and now it works perferct

Rod

Wednesday, March 7, 2012

Data-Driven Subscription - Empty Field List on Step 4

I am attempting to create a data-driven subscription. I step through the
wizard, paste in the query, validate and click next. When I get to the screen
to map the fields from the database table to the fields in the subscription
(to, cc, reply-to, etc).
There are no fields in the drop-down. I have tried numerous different
queries, that I know work when I run them in a report, but don't seem to want
to populate the field list. The source database is Teradata, if that makes a
difference.
There is no error, and I can't seem to find any log entries, so I am not
sure where to turn. Any Ideas?
SteveUPDATED: I have confirmed that, in fact the data-driven subscription will
pull fields from SQL Server, so the issue seems to be with the Teradata
connection.
Any help?
"Steve Muise" wrote:
> I am attempting to create a data-driven subscription. I step through the
> wizard, paste in the query, validate and click next. When I get to the screen
> to map the fields from the database table to the fields in the subscription
> (to, cc, reply-to, etc).
> There are no fields in the drop-down. I have tried numerous different
> queries, that I know work when I run them in a report, but don't seem to want
> to populate the field list. The source database is Teradata, if that makes a
> difference.
> There is no error, and I can't seem to find any log entries, so I am not
> sure where to turn. Any Ideas?
> Steve

Dataconversion: STRING (yyyymmdd) to DATE

Hi All,

I need a solution for the following:

I have a field with data type string, length 8, in the form yyyymmdd (f.e. 20070604).

Now I need to transfer this field into a field with data type DATE.

I know the function DATESERIAL in MS ACCESS but what is the equivalent function in TSQL?

Any hint for me is very

Thanks in Advance

ulrike

You just need to make sure DATEFORMAT is set to match the incoming data and then perform a conversion.

Code Snippet

setDATEFORMAT ymd

selectconvert(datetime,'20070604')as d1,cast('20070604'asdatetime)as d2

|||

You could use CONVERT function with 112 style:

Code Snippet

declare @.dt varchar(20)

set @.dt ='20070507'

selectconvert(datetime,@.dt,112)

|||

Hello again,

Thanks for your advise.

I tried to run the following code:

selectconvert(datetime,whuser.[tbl_source].EffectiveDate_str,112)as EffectiveDate_dt

into WHUser.[tbl_target]

from WHUser.[tbl_source]

BUT it terminated with error:

“The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value”.

What’s going wrong? Please give me some mor advise.

Thanks in advance,

ulrike

|||

Hi ulrikeG,

SQL Server will convert that value implicitly without any problem. You are using the ISO format and SQL Server will interprete it corrrectly, no matter the language or settings of dateformat being used.

Code Snippet

create table dbo.t1 (

c1 char(8) null,

c2 datetime null

)

go

insert into dbo.t1(c1) values('20070606')

go

select * from dbo.t1

go

update dbo.t1

set c2 = c1

go

select * from dbo.t1

go

drop table dbo.t1

go

AMB

|||

ulrikeG wrote:

“The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value”.

Maybe there's bad data in your table.

Try running a query WHERE IsDate (string) = 0.

|||Change your code to:

Code Snippet

select CASE WHEN ISDATE(whuser.[tbl_source].EffectiveDate_str) = 1 THENconvert(datetime,whuser.[tbl_source].EffectiveDate_str,112) ELSE NULL ENDas EffectiveDate_dt

into WHUser.[tbl_target]

from WHUser.[tbl_source]

Then:
SELECT * FROMWHUser.[tbl_target] WHERE EffectiveDate_dt IS NULL
to find the errors

Sunday, February 26, 2012

DataBinding with Insert query problem

Hello,

I have a page with a detailsview where I can add articles (Generated by visual studio). Now the table contains a field (Autor) wich must contain the username of the Autor from the article. But when I run my page now I have to give it in manually ( in a textbox). I've searching for a way to bind the Profile Username with the insert Sql Query, @.Autor value.

I tought maybe I should insert the value of the Profile username in the textbox and put the textbox visibel on false.

But When i saw the component code I saw that Text= is already bound, so it's not possible to insert a value

<asp:TextBox ID="auteurTextBox" Visible="true" runat="server" Text='<%# Bind("auteur")%>'>
 Here is whole the page code (line 23 is the textbox).
 
1<asp:FormView ID="FormView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1" AllowPaging="True" CellPadding="4" ForeColor="#333333" style="left: 30%; position: relative">2 <EditItemTemplate>3 <asp:Label ID="idLabel1" Visible="false" runat="server" Text='<%# Eval("id")%>'></asp:Label>4 <asp:TextBox ID="auteurTextBox" Visible="false" runat="server" Text='<%# Bind("auteur")%>'>5 </asp:TextBox>6 soort:7 <asp:TextBox ID="soortTextBox" runat="server" Text='<%# Bind("soort")%>'>8 </asp:TextBox><br />9 titel:10 <asp:TextBox ID="titelTextBox" runat="server" Text='<%# Bind("titel")%>'>11 </asp:TextBox><br />12 text:13 <asp:TextBox ID="textTextBox" Height="200px" TextMode="MultiLine" Rows="20" Width="260px" runat="server" Text='<%# Bind("text")%>'>14 </asp:TextBox><br />15 <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update"16 Text="Update">17 </asp:LinkButton>18 <asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"19 Text="Cancel">20 </asp:LinkButton>21 </EditItemTemplate>22 <InsertItemTemplate>23 <asp:TextBox ID="auteurTextBox" Visible="true" runat="server" Text='<%# Bind("auteur")%>'>24 </asp:TextBox><br />25 Soort:26 <asp:TextBox ID="soortTextBox" runat="server" Text='<%# Bind("soort")%>'>27 </asp:TextBox><br />28 titel:29 <asp:TextBox ID="titelTextBox" runat="server" Text='<%# Bind("titel")%>'>30 </asp:TextBox><br />31 text:32 <asp:TextBox ID="textTextBox" runat="server" Text='<%# Bind("text")%>'>33 </asp:TextBox><br />34 <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"35 Text="Insert">36 </asp:LinkButton>37 <asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"38 Text="Cancel">39 </asp:LinkButton>40 </InsertItemTemplate>41 <ItemTemplate>42 <asp:Label ID="idLabel" Visible="false" runat="server" Text='<%# Eval("id")%>'></asp:Label><br />43 <asp:Label ID="auteurLabel" Visible="false" runat="server" Text='<%# Bind("auteur")%>'></asp:Label><br />44 soort:45 <asp:Label ID="soortLabel" runat="server" Text='<%# Bind("soort")%>'></asp:Label><br />46 titel:47 <asp:Label ID="titelLabel" runat="server" Text='<%# Bind("titel")%>'></asp:Label><br />48 text:49 <asp:Label ID="textLabel" runat="server" Text='<%# Bind("text")%>'></asp:Label><br />50 <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit"51 Text="Edit">52 </asp:LinkButton>53 <asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete"54 Text="Delete">55 </asp:LinkButton>56 <asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New"57 Text="New">58 </asp:LinkButton>59 </ItemTemplate>60 <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />61 <EditRowStyle BackColor="#2461BF" />62 <RowStyle BackColor="#EFF3FB" />63 <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />64 <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />65 </asp:FormView>66 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"67 ConnectionString="<%$ ConnectionStrings<img src="http://pics.10026.com/?src=images/smilies/biggrinn.gif" border="0" alt="">atabankConnectie%>" DeleteCommand="DELETE FROM [artikel2] WHERE [id] = @.original_id AND [auteur] = @.original_auteur AND [soort] = @.original_soort AND [titel] = @.original_titel AND [text] = @.original_text"68 InsertCommand="INSERT INTO [artikel2] ([auteur], [soort], [titel], [text]) VALUES (@.auteur, @.soort, @.titel, @.text)"69 OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [artikel2] WHERE [auteur] = @.auteur"70 UpdateCommand="UPDATE [artikel2] SET [auteur] = @.auteur, [soort] = @.soort, [titel] = @.titel, [text] = @.text WHERE [id] = @.original_id AND [auteur] = @.original_auteur AND [soort] = @.original_soort AND [titel] = @.original_titel AND [text] = @.original_text">71 <DeleteParameters>72 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_id" Type="Int32">73 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_auteur" Type="String">74 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_soort" Type="String">75 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_titel" Type="String">76 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_text" Type="String">77 </DeleteParameters>78 <UpdateParameters>79 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="auteur" Type="String">80 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="soort" Type="String">81 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="titel" Type="String">82 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="text" Type="String">83 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_id" Type="Int32">84 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_auteur" Type="String">85 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_soort" Type="String">86 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_titel" Type="String">87 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="original_text" Type="String">88 </UpdateParameters>89 <InsertParameters>90 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="auteur" Type="String">91 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="soort" Type="String">92 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="titel" Type="String">93 <asp src="images/smilies/tongue.gif" border="0" alt="">arameter Name="text" Type="String">94 </InsertParameters>95 </asp:SqlDataSource>96 </LoggedInTemplate>97 </asp:LoginView>98</asp:Content>99
Can somebody help me?

Hi,

instead of doing that in the asp code, you could achieve the same goal in the code behind:

1. Removed the insert parameter 'auteur' for the asp code

2. add in the page load event the following code:

protected void Page_Load(object sender, EventArgs e)
{

SqlParameter param = new SqlParameter("auteur", SqlDbType.NVarChar);
param.Value = Profile.UserName;

SqlDataSource1.InsertParameters.Add(param);
}

It may need some adjustment to meet your needs but I believe you got the idea :)

Cheers,

Yani

|||

Im having the exact same problem and Im a Newbie......i can't send the profile.username into the d.b. Could it be possible to elaborate a bit, my detailsview looks almost identical. I've spent two frustrating days and hope to have this figured out........... is there a way to put it into the sql insert statement?? im not the best coder by far!

Thanks!

|||

i tried using your example but keep getting errors

SqlParameter

param =newSqlParameter("profile",SqlDbType.NVarChar);

param.Value = Profile.UserName;

SqlDataSource1.InsertParameters.Add(param);

it keeps telling me that

Error 1 The best overloaded method match for 'System.Web.UI.WebControls.ParameterCollection.Add(System.Web.UI.WebControls.Parameter)' has some invalid arguments C:\Documents and Settings\Karl\My Documents\Visual Studio 2005\WebSites\WebSite_fitness\Members\diet_journal.aspx.cs 21 9 C:\...\WebSite_fitness\

Error 2 Argument '1': cannot convert from 'System.Data.SqlClient.SqlParameter' to 'string' C:\Documents and Settings\Karl\My Documents\Visual Studio 2005\WebSites\WebSite_fitness\Members\diet_journal.aspx.cs 21 45 C:\...\WebSite_fitness\

im totally helpless and frustrated....please help!!

|||

The SelectParameters collection is not a collection of SqlParameter. Use another overload of the add function:

SqlDataSource1.InsertParameters.Add("profile",Profile.UserName);

Cheers,

Yani

|||

Thanks Yani, appreciate it... im going to try it when I get home. is it possible to use it in the asp detailsview? basically i bind a textbox during insert and have this problem...... either i can set the to text = bind("profile") or text= membership.get()username. The latter returns my username but wont insert it into my table...lol im quite frustrated and my experience is somewhat lacking..... i use the controls kinda out of the box.......

thanks again !

|||

if maybe u can help with the asp aspect...... this is what my code looks like.... i cant get your page load event to work...... can u maybe walk me through step by step... im really having a rough time!

Thanks!!

<%

@.PageLanguage="C#"MasterPageFile="~/Members/MasterPage.master"AutoEventWireup="true"CodeFile="diet_journal.aspx.cs"Inherits="Members_diet_journal"Title="Untitled Page" %>

<

asp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"Runat="Server"> Diet Journal<br/> <asp:DetailsViewID="DetailsView1"runat="server"AutoGenerateRows="False"DataKeyNames="meal_hist_id_pk"DataSourceID="SqlDataSource1"Height="50px"Style="position: static"Width="125px"DefaultMode="Insert"><Fields><asp:BoundFieldDataField="meal_hist_id_pk"HeaderText="meal_hist_id_pk"InsertVisible="False"ReadOnly="True"SortExpression="meal_hist_id_pk"/><asp:TemplateFieldHeaderText="date"SortExpression="date"><EditItemTemplate><asp:TextBoxID="TextBox2"runat="server"Text='<%# Bind("date") %>'></asp:TextBox></EditItemTemplate><InsertItemTemplate><asp:CalendarID="Calendar1"runat="server"SelectedDate='<%# Bind("date") %>'Style="position: static"></asp:Calendar></InsertItemTemplate><ItemTemplate><asp:LabelID="Label2"runat="server"Text='<%# Bind("date") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:BoundFieldDataField="meal_des_fk"HeaderText="meal_des_fk"SortExpression="meal_des_fk"/><asp:TemplateFieldHeaderText="profile"SortExpression="profile"><EditItemTemplate><asp:TextBoxID="TextBox1"runat="server"Text='<%# Bind("profile") %>'></asp:TextBox></EditItemTemplate><InsertItemTemplate><asp:TextBoxID="TextBox1"runat="server"Text='<%# bind("profile") %>'></asp:TextBox></InsertItemTemplate><ItemTemplate><asp:LabelID="Label1"runat="server"Text='<%# Bind("profile") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:BoundFieldDataField="calories"HeaderText="calories"SortExpression="calories"/><asp:BoundFieldDataField="fat"HeaderText="fat"SortExpression="fat"/><asp:BoundFieldDataField="carbs"HeaderText="carbs"SortExpression="carbs"/><asp:BoundFieldDataField="protein"HeaderText="protein"SortExpression="protein"/><asp:BoundFieldDataField="fibre"HeaderText="fibre"SortExpression="fibre"/><asp:CommandFieldShowInsertButton="True"/></Fields></asp:DetailsView><asp:SqlDataSourceID="SqlDataSource1"runat="server"ConflictDetection="CompareAllValues"ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\diet_journal.mdf;Integrated Security=True;User Instance=True"DeleteCommand="DELETE FROM [meal_history] WHERE [meal_hist_id_pk] = @.original_meal_hist_id_pk AND [date] = @.original_date AND [meal_des_fk] = @.original_meal_des_fk AND [profile] = @.original_profile AND [calories] = @.original_calories AND [fat] = @.original_fat AND [carbs] = @.original_carbs AND [protein] = @.original_protein AND [fibre] = @.original_fibre"InsertCommand="INSERT INTO [meal_history] ([date], [meal_des_fk], [profile], [calories], [fat], [carbs], [protein], [fibre]) VALUES (@.date, @.meal_des_fk, @.profile, @.calories, @.fat, @.carbs, @.protein, @.fibre)"OldValuesParameterFormatString="original_{0}"ProviderName="System.Data.SqlClient"SelectCommand="SELECT [meal_hist_id_pk], [date], [meal_des_fk], [profile], [calories], [fat], [carbs], [protein], [fibre] FROM [meal_history]"UpdateCommand="UPDATE [meal_history] SET [date] = @.date, [meal_des_fk] = @.meal_des_fk, [profile] = @.profile, [calories] = @.calories, [fat] = @.fat, [carbs] = @.carbs, [protein] = @.protein, [fibre] = @.fibre WHERE [meal_hist_id_pk] = @.original_meal_hist_id_pk AND [date] = @.original_date AND [meal_des_fk] = @.original_meal_des_fk AND [profile] = @.original_profile AND [calories] = @.original_calories AND [fat] = @.original_fat AND [carbs] = @.original_carbs AND [protein] = @.original_protein AND [fibre] = @.original_fibre"OnSelecting="SqlDataSource1_Selecting"><DeleteParameters><asp:ParameterName="original_meal_hist_id_pk"Type="Int32"/><asp:ParameterName="original_date"Type="DateTime"/><asp:ParameterName="original_meal_des_fk"Type="Int32"/><asp:ParameterName="original_profile"Type="String"/><asp:ParameterName="original_calories"Type="Int32"/><asp:ParameterName="original_fat"Type="Int32"/><asp:ParameterName="original_carbs"Type="Int32"/><asp:ParameterName="original_protein"Type="Int32"/><asp:ParameterName="original_fibre"Type="Int32"/></DeleteParameters><UpdateParameters><asp:ParameterName="date"Type="DateTime"/><asp:ParameterName="meal_des_fk"Type="Int32"/><asp:ParameterName="profile"Type="String"/><asp:ParameterName="calories"Type="Int32"/><asp:ParameterName="fat"Type="Int32"/><asp:ParameterName="carbs"Type="Int32"/><asp:ParameterName="protein"Type="Int32"/><asp:ParameterName="fibre"Type="Int32"/><asp:ParameterName="original_meal_hist_id_pk"Type="Int32"/><asp:ParameterName="original_date"Type="DateTime"/><asp:ParameterName="original_meal_des_fk"Type="Int32"/><asp:ParameterName="original_profile"Type="String"/><asp:ParameterName="original_calories"Type="Int32"/><asp:ParameterName="original_fat"Type="Int32"/><asp:ParameterName="original_carbs"Type="Int32"/><asp:ParameterName="original_protein"Type="Int32"/><asp:ParameterName="original_fibre"Type="Int32"/></UpdateParameters><InsertParameters><asp:ParameterName="date"Type="DateTime"/><asp:ParameterName="meal_des_fk"Type="Int32"/><asp:ParameterName="profile"Type=String/><asp:ParameterName="calories"Type="Int32"/><asp:ParameterName="fat"Type="Int32"/><asp:ParameterName="carbs"Type="Int32"/><asp:ParameterName="protein"Type="Int32"/><asp:ParameterName="fibre"Type="Int32"/></InsertParameters></asp:SqlDataSource><br/>|||

Hi,

when you add parameters from the code behind like this :

SqlDataSource1.InsertParameters.Add("profile",Profile.UserName);

you need to remove the asp tag for that parameter from the aspx page:

<asp:ParameterName="profile"Type=String/>

From <InsertParameters> tag.

Cheers,

Yani

|||Thanks once again yani, I'll be trying that once i get home!! So if i understand correctly, i need to add

SqlDataSource1.InsertParameters.Add("profile",Profile.UserName); inside of the page load event

and remove<asp:ParameterName="profile"Type=String/>....... from the aspx page. For the insert command and values, do i keep @.profile??

also, for my insert template for the textbox...... do i leave it as bind(profile) ?

Thanks a million for taking the time with me, its greatly appreciated...... I'll owe you at least a case of beer!

Karl

|||

Well,

let me try to explain a lil bit more.

So you have for the InsertParameters in the asp code(aspx) sth like:

<InsertParameters>

// some parameters

<asp:ParameterName="profile"Type=String/>

// some parameters

</InsertParameters>

When you compile the whole web site, the aspx pages are parsed and transformed into code, sth like

public class YourPageNameHere: Page

{

// some functions

//

SqlDataSource1.InsertParameters.Add(paramName, paramvalue);

}

but in your case

<asp:ParameterName="profile"Type=String/>

you have not specified the value here.

So it does not know what to put here.

So instead of doing that in the asp code.

you could do it in the code behind.

SqlDataSource1.InsertParameters.Add("profile",Profile.UserName);

(in the page load function);

where Profile object is accessible.

For the insert command and values, do i keep @.profile??

also, for my insert template for the textbox...... do i leave it as bind(profile) ?

In the insert command - it should remain - since it is the pure sql statement. So keep it as is.

For the insert template...i think you should remove it... actually what are you trying to do there ?

to put as parameter @.profile - the name entered in the text box, or the Profile.UserName ?!

If it is the first you could do sth like:

<asp:ControlParameter ControlID="TextBox1" PropertyName="Text" Name="profile" Type="string" />

Where TextBox1 is the ID of the TextBox control that will be used for entering the profile name.

If this does not solve the problem , please clarify what are you trying to accomplish exactly.

Cheers,

Yani

|||

Awesome, your explanation really cleared things up.... thank you for being super patient and so clear on your explanations...... I'll try this as soon as i get home!.... I can't wait to get this up and running!!

Karl

|||

Hi again, I just tried what you had suggested.........

and keep getting this error

Cannot insert the value NULL into column 'profile', table 'C:\DOCUMENTS AND SETTINGS\KARL\MY DOCUMENTS\VISUAL STUDIO 2005\WEBSITES\WEBSITE_FITNESS\APP_DATA\DIET_JOURNAL.MDF.dbo.meal_history'; column does not allow nulls. INSERT fails.
The statement has been terminated.

Im using your page load event like this :

protectedvoid Page_Load(object sender,EventArgs e)

{

newSqlParameter("profile",SqlDbType.NVarChar);

SqlDataSource1.InsertParameters.Add(

"profile", Profile.UserName);

}

and my asp code looks like this:

<%

@.PageLanguage="C#"MasterPageFile="~/Members/MasterPage.master"AutoEventWireup="true"CodeFile="diet_journal.aspx.cs"Inherits="Members_diet_journal"Title="Untitled Page" %>

<

asp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"Runat="Server"> Diet Journal<br/> <asp:DetailsViewID="DetailsView1"runat="server"AutoGenerateRows="False"DataSourceID="SqlDataSource1"DefaultMode="Insert"Height="50px"Style="position: static"Width="125px"><Fields><asp:TemplateFieldHeaderText="date"SortExpression="date"><EditItemTemplate><asp:TextBoxID="TextBox1"runat="server"Text='<%# Bind("date") %>'></asp:TextBox></EditItemTemplate><InsertItemTemplate><asp:CalendarID="Calendar1"runat="server"SelectedDate='<%# Bind("date") %>'Style="position: static"></asp:Calendar></InsertItemTemplate><ItemTemplate><asp:LabelID="Label1"runat="server"Text='<%# Bind("date") %>'></asp:Label></ItemTemplate></asp:TemplateField><asp:BoundFieldDataField="profile"HeaderText="profile"SortExpression="profile"/><asp:CommandFieldShowInsertButton="True"/></Fields></asp:DetailsView><asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\diet_journal.mdf;Integrated Security=True;User Instance=True"InsertCommand="INSERT INTO meal_history(date, profile) VALUES (@.date, @.profile)"ProviderName="System.Data.SqlClient"SelectCommand="SELECT [date], [profile] FROM [meal_history]">

</asp:SqlDataSource><br/>

</asp:Content>

To make it simple i just want to insert the date and profile.username............. I keep getting the null profile error though ...i dont know why it wont pass my value to the d.b

Im sorry if Im not getting it, I thought I was a little smarter than this but this problem is kicking my butt!!!

Karl

|||

SUCCESS!!! I got it to work, I used your explaination and I went about it a little bit differently

for the page load i used........

SqlDataSource1.InsertParameters.Add(

"profile",Membership.GetUser().UserName);

and it works.....I guess the profile.name wasn't what i needed, but I did remove the other insert parameter from the aspx page....."profile"

Thank you soooooo much ........I didnt realize thatI have so much to learn!

|||

Hi Karl,

it's great you did it on your own :) but not just copying sth from someone that you don't understand.

We all study each day, so there is much left to be learnt ;)

Cheers,

Yani

|||

Very true Yani !!

Thanks again for all the patience and help, it is very much appreciated!

Have a great day,

Karl

Tuesday, February 14, 2012

Database triggers - SQL Server - Fields only allowed if listed in another field in another

I would like to ensure data integrity in a column (actually multiple columns will need a trigger) in my table(s) by setting up a trigger which allows an update of my database field only if the value which is being written to the field in the database exists in another column (in another "check" table).

eg. I only want values "Yes", "No" or "" in many of my fields, which I store in a column named "YesNoBlank" in another table.

Does anyone know the easy way to do this? / Syntax for the trigger?

Why not use PK/FK instead of trigger? I mean you can define the YesNoBlank column as Primary Key in some table, and other columns whose values must exist in the YesNoBlank column as Foreign Key referenceing the YesNoBlank column. For more information about PK/FK, you can take a look at:

Creating and Modifying FOREIGN KEY Constraints

|||

I think Check constraints are my preferance, as I have all of my fields which would potentially be Primary keys in your example in a single reference table (ie multiple columns)

My statement in('Yes','No','') does not work for my check constraint.

Does anyone know what my syntax would be?

|||A quick sample:

CREATE TABLE testConstraint (ID INT, NAME sysname, YESNO VARCHAR(3))

ALTER TABLE testConstraint
ADD CONSTRAINT yesno_check CHECK (UPPER(YESNO) in ('YES','NO'))

--This will succeed
INSERT INTO testConstraint VALUES(1,'Iori','Yes')
--This will fail
INSERT INTO testConstraint VALUES(2,'Kyo','noo')

For mor information, you can refer to:?ALTER?TABLE?