Please Critique My Work

Feb 23, 2007

Hi,

I would really appreciate any constructive criticism of my sql script (see end of message).

I have been working for a week to pull data from a database that has evolved over the years. It might have been designed to begin with, but it has had a lot of changes made on the fly, which makes pulling some data from it very hard.

One example is that they wanted Primary Service for a given client but this data was not stored in a base client table, but was instead on a table with multiple rows per client. To pick the row that referenced the correct Primary Service I had to:
1. Join the Client table with the view on client number and primary program number
2. From the records returned look at another column (proc_cde) in the view and pick the one that had a higher priority than the others. The precedence order of the proc_cdes was determined by a list my boss gave me. I used this forum to help me figure this part out.

Anyway … I finally got it done and it works … but just because it works doesn't mean it is well written. What I would like is if some of you could take a look at the sql and critique it for good and/or bad practices.

The design of the database is a given (and not my doing) so I am not looking for a critique of it.

An Example of what I am asking for would be:
I ended up using temp tables to collect some of the more complicated data so that I could write a very straightforward final query. Was this a good or bad thing and if bad why?

I really want to get good at sql and avoid developing any bad habits, so please critique my sql.

Also please ask me any questions that could help you evaluate the code.

Thanks,

Laurie

Note: the comments at the top were all the specs I got for creating this report (they came in an email).

/*detail- primary clincian/provider priemp_num joined to facemp Y
primary service (act,cm,opt), pripgm_num primary program,
select proc_cde from v_autsvc join svc
on proc_cde where pgm_num=pripgm_num
H0039 then T1017 t1016 then H0036
location of service, pgm_num of 90862 auth
date of auth v_autsvc.aut_dte
cons name/number: CLTCLT
auth date range v_autsvc.autbeg_dte v_autsvc.autend_dte
number of claims in the last fiscal year v_clmsvc, count(*)
primary psycchiatrist. cltdmo.pspemp_num join phy on phy_num


select clt_num, count(*) as num_claims from v_clmsvc
where beg_dte between '10/1/2005' and '9/30/2006 23:59'
group by clt_num

tables: v_autsvc, pgm, cltdmo.population='mi adult'
proc_cde in ('90862','90801')
autend_Dte>'10/1/06'

I need a report showing all Adult MI consuemrs receiving psych services by agency- like the
aggregate and detail of who gets them at where-bridgeways, sr srv... including our clinic.

i would need in the detail- primary clincian/provider, primary service (act,cm,opt), location of service,
date of auth, cons name/number, auth date range/# of units and number of claims in the last fiscal year and
primary psycchiatrist. if xxx asks for something similar, let me know as we might be duplicating.

i know that xxx is going to be asking for a report that is for just our clinic that has more to do with
insurance type. if it would be easier, you could combine the 2 reports as long as we have the capacity
to sort and print by provider. thanks*/

/**********************************************************************************
Primary Service
***********************************************************************************/
-- select primary proc_cde for primary service Candidates
drop table #ConsumerProcCodes
select distinct a.clt_num,
a.proc_cde,
a.aut_dte,
a.autbeg_dte,
a.autend_dte
into #ConsumerProcCodes
from cltdmo d join v_autsvc a on a.clt_num = d.clt_num
and d.pripgm_num = a.pgm_num
and a.autsts = 1
and getdate() between a.autbeg_dte and a.autend_dte


-- create table of ProcCde Precedence
drop table #ProcCde_Precedence
create table #ProcCde_Precedence
(proc_cde varchar(10),
Precedence int)

insert #ProcCde_Precedence
(proc_cde,Precedence)
select 'H0039', 10 union all
select 'T1017', 20 union all
select 'T1016', 30 union all
select 'H0036', 40 union all
select 'T2011', 50 union all
select '90806', 60 union all
select '90862', 70 union all
select 'T1002', 80 union all
select 'H2031', 90 union all
select 'H2023', 100 union all
select 'H2015', 110 union all
select 'T1005', 120

-- assign precedence to proc_cde
drop table #ConsumerProcCodesWPrec
select distinct c.clt_num,
c.aut_dte,
c.autbeg_dte,
c.autend_dte,
case when p.Precedence is null then 1000
else p.Precedence
end as Precedence,
left(c.proc_cde,5) as proc_cde
into #ConsumerProcCodesWPrec
from #ConsumerProcCodes c left join #ProcCde_Precedence p on p.proc_cde = left(c.proc_cde,5)

-- select primary proc_cde for each consumer and get associated PrimaryService
drop table #PrimaryService
select distinct p1.clt_num,
p1.proc_cde,
p1.aut_dte,
p1.autbeg_dte,
p1.autend_dte,
s.acttyp_des as PrimaryService
into #PrimaryService
from #ConsumerProcCodesWPrec p1 join svc s on p1.proc_cde = s.proc_cde
where Precedence = (select min(Precedence)
from #ConsumerProcCodesWPrec p2
where p1.clt_num = p2.clt_num)

-- Find Consumers with more than one primary Proc_cde
/*
select clt_num, proc_cde, aut_dte, autbeg_dte, autend_dte
from #PrimaryService
where clt_num in (select clt_num
from #PrimaryService
group by clt_num
having sum(1) > 1)
*/
/**********************************************************************************
Primary Location
***********************************************************************************/
-- select pgm_num for Primary location Candidates
drop table #ConsumerLOS
select distinct a.clt_num,
a.pgm_num,
p.pgm_nme
into #ConsumerLOS
from v_autsvc a join pgm p on a.pgm_num = p.pgm_num
where a.autsts = 1
and getdate() between a.autbeg_dte and a.autend_dte
and a.proc_cde = '90862'

-- create table of pgm_num for Location of Services Precedence
drop table #LOS_Precedence
create table #LOS_Precedence
(pgm_num int,
Precedence int)

insert #LOS_Precedence
(pgm_num,Precedence)
select 5600, 10 union all
select 6200, 20 union all
select 6000, 30 union all
select 1611, 40 union all
select 1612, 50 union all
select 1601, 60

-- assign precedence to pgm_num
drop table #ConsumerLOSwPrecedence
select distinct c.clt_num,
case when p.Precedence is null then 1000
else p.Precedence
end as Precedence,
c.pgm_num
into #ConsumerLOSwPrecedence
from #ConsumerLOS c left join #LOS_Precedence p on p.pgm_num = c.pgm_num


-- select pgm_num for primary location of Services for each consumer
drop table #PrimaryLOS
select distinct p1.clt_num,
case n.NumRows
when 1 then cast(p1.pgm_num as varchar(10))
else cast(p1.pgm_num as varchar(10)) + '*'
end as LocationOfService
into #PrimaryLOS
from #ConsumerLOSwPrecedence p1 join (select clt_num,count(*) as NumRows
from #ConsumerLOSwPrecedence
group by clt_num) n on p1.clt_num = n.clt_num
where Precedence = (select min(Precedence)
from #ConsumerLOSwPrecedence p2
where p1.clt_num = p2.clt_num)



-- Find Consumers with more than one primary pgm_cde for Location of Services.
/*select distinct clt_num from #PrimaryLOS
select * from #PrimaryLOS
where clt_num in (select clt_num
from #PrimaryLOS
group by clt_num
having sum(1) > 1)*/

/**********************************************************************************
Put it all together
***********************************************************************************/
drop table #FinalResults
select distinct c.clt_num,
c.fst_nme + ' ' + c.lst_nme as ConsumerName,
f.fst_nme + ' ' + f.lst_nme as PrimaryClinician,
p.fst_nme + ' ' + p.lst_nme as PrimaryPsychiatrist,
ps.PrimaryService,
COALESCE(n.num_claims,0) as num_claims,
los.LocationOfService,
ps.aut_dte,
ps.autbeg_dte,
ps.autend_dte
into #FinalResults
from cltctl c join cltdmo d on c.clt_num = d.clt_num and d.population = 'mi adult'
join v_autsvc a on c.clt_num = a.clt_num
and a.autsts = 1
and getdate() between a.autbeg_dte and a.autend_dte
and a.proc_cde in ('90862','90801')
join facemp f on d.priemp_num = f.facemp_num
left join phy p on d.pspemp_num = p.phy_num
left join #PrimaryService ps on ps.clt_num = c.clt_num
left join (select clt_num, count(*) as num_claims
from v_clmsvc
where beg_dte between '10/1/2005' and '9/30/2006 23:59'
group by clt_num) n on c.clt_num = n.clt_num
left join #PrimaryLOS los on c.clt_num = los.clt_num
order by c.clt_num

select * from #FinalResults
/*
select * from #FinalResults
where PrimaryService is null

select * from #FinalResults
where LocationOfService is null

select * from #FinalResults
where PrimaryPsychiatrist is null

select * from #FinalResults
where PrimaryClinician is null

select * from #FinalResults
where num_claims = 0

*/

edited to make word wrap work

View 5 Replies


ADVERTISEMENT

Trigger Critique

May 21, 2004

Here is a trigger I wrote to check for duplicate taxid's in my producer table. Duplicate taxid's with an '' value are allowed. I'm green when it comes to trigger coding so would anyone care to review my code and reply if there's a more efficient way to implement the trigger or handle errors.

Thanks PLJ

create trigger dbo.tib_producer on dbo.producer for insert as
begin
declare
@numrows int,
@errno int,
@errmsg varchar(255)
select @numrows = @@rowcount
if @numrows = 0
return
/* Check for duplicate tax_id if inserted is not null */
if update(tax_id)
begin
if exists(select tax_id
from producer
where tax_id in (select tax_id
from inserted)
and tax_id <> ''
group by tax_id having count(*)>1)
begin
select @errno = 50002,
@errmsg = 'Tax ID already Exists'
goto error
end

end
return
/* Errors handling */
error:
raiserror @errno @errmsg
rollback transaction
end

View 3 Replies View Related

Query Critique

Jul 23, 2005

I just finished a new query where I summarized detail information. I'mwondering if I did this really awkwardly or is this a common way towrite SQL? I've cross referenced the end results and the data seemsconsistant, so I am happy with the results.TIASELECTSESSION_ID,CAMPUS_ID,SUM(STUDENT_COUNT) AS STUDENT_COUNT,SUM(NEW_STUDENT) AS NEW_STUDENT_COUNTFROM (SELECTSESSION_ID,STUDENT_ID,CAMPUS_ID ,STUDENT_COUNT ,STUDENT_STARTING_SESSION_ID,NEW_STUDENT = CASE WHEN SESSION_ID=STUDENT_STARTING_SESSION_IDTHEN (1) ELSE (0) ENDFROM (selectSESSION_ID,STUDENT_ID,CAMPUS_ID ,STUDENT_COUNT ,STUDENT_STARTING_SESSION_IDFROM(selectSESSION_ID,STUDENT_ID,CAMPUS_ID = (SELECT STUDENT_CAMPUS_ID FROMD_BI_STUDENT WHERE A.STUDENT_SKEY=D_BI_STUDENT.STUDENT_SKEY) ,STUDENT_COUNT = DAY0_CLASS_COUNT,(select student_starting_session_id fromf_bi_student_statistics where A.student_id =f_bi_student_statistics.student_id) as 'STUDENT_STARTING_SESSION_ID'from f_bi_registration_tracking_summary A) AS XWHERE STUDENT_COUNT > 0GROUP BY SESSION_ID, STUDENT_ID, CAMPUS_ID, STUDENT_COUNT,STUDENT_STARTING_SESSION_ID) AS Y) AS ZGROUP BY SESSION_ID, CAMPUS_ID

View 3 Replies View Related

Can Someone Critique My Sql Relationship Structure?

Jun 6, 2008

I was building out my db and then ran into a problem updating a primary key value. I then started to doubt whether or not I even did this right. To simplify, I"m going to just create a smaller similar scenario and I just want to know if its right
 Lets say I have three tables
Order Tableordernum (PK)orderdateorderamt
Phone TablePhonenumber (PK)ordernum (FK)NumbertypeInternet TableCircuitID (PK)Phonenumber(PK)IPSMGW
now, Instead of creating a seperate column for just an incrementing numeric value as a PK i used the order number, phone number, and circuit id's as the Primary keys since every single value will be unique. Plus, I also did it to prevent duplicates. Now the problem I'm having is, when I do Update db set [phonenumber] = @phonenumber, ordernum = @ordernum, numbertype = @numbertype where phonenumber = @phonenumber as wrong as that looks.
It looks wrong to me.. problably why it doesn't work. How do you change the values of primary keys.. or should I have created a column called ID with incrementing numbers. How would I prevent duplicates then?

View 5 Replies View Related

1st Attempt, Designing, Would Like Somebody To Review And Critique It

Jan 23, 2001

Hello

This is my 1st attempt at designing a database, and I have not finished
it completely, but I would like somebody to review and critique for me.
I really don't want to make any mistakes with this and I would appreciate any expertise out there to direct, recommend, suggest improvements and/or changes, PLEASE.

Thank you for considering this,,,if you provide me with your e-mail, I can send you a script.

take care,
~Iris~
:)

View 1 Replies View Related

Expert's Critique On Package Design

Aug 31, 2007

All:
This proably is an unsual request. I have developed a package that runs fine and does what it is supposed to do. I am jsut not sure if I have developed it in the most efficient way. I have several years of ETL experience but only about 6 months with SSIS. I know I can benefit a lot if I had my package reviewed by an expert.

I realize that I am asking for some time committment on your part and so would understand if I do not get any takers. But if you would like to review my package and offer suggestions on its improvement please let me know. We can work on the logistics of getting the package to you.

Thanks!

View 7 Replies View Related

Why Does This Not Work

Feb 27, 2007

 My error is that 'Name tr is not declared'  tr.Rollback() I tried moving the 'Dim tr As SqlTransaction' outside the try but then I get 'Variable tr is used before it si assinged a value'.
What is the correct way?        Try            conn.Open()            Dim tr As SqlTransaction            tr = conn.BeginTransaction()            cmdInsert1.Transaction = tr            cmdInsert1.ExecuteNonQuery()            cmdInsert2.Transaction = tr            cmdInsert2.ExecuteNonQuery()            cmdInsert3.Transaction = tr            cmdInsert3.ExecuteNonQuery()            tr.Commit()        Catch objException As SqlException           tr.Rollback()            Dim objError As SqlError            For Each objError In objException.Errors                Response.Write(objError.Message)            Next        Finally            conn.Close()        End Try 

View 5 Replies View Related

Can't Get LIKE To Work

Apr 19, 2007

I have the below procedure that will not work- I must be losing my mind, this is not that difficult - mental roadblock for me.
Using SQL Server 2000 to create SP being called by ASP.Net with C# code behind
stored procedure only returns if input exactly matches L_Name
PROCEDURE newdawn.LinkNameLIKESearch @L_Name nvarchar(100)AS SELECT [L_Name], [L_ID], [C_ID], [L_Enabled], [L_Rank], [L_URL] FROM tblContractorLinkInfo WHERE L_Name LIKE @L_Name RETURN
I tried: WHERE L_Name LIKE ' % L_Name % '  no luck. What am I missing?
Thank you
 

View 2 Replies View Related

SP Does Not Work.

May 24, 2007

SP below is not work.It gives null for @kaysay 
I used parametric table name. Is this the problem? 
My aim to calculate record count of a table
Thanks. 
 
CREATE PROCEDURE Tablodaki_Kayit_Sayisi(@TABLO varchar(30))AS
Declare @kaysay bigintDeclare @SQLString nvarchar(100)Declare @Param nvarchar(100)
Set @SQLString = N'Select @kaysayOUT = count(BELGE) From ' + @TABLOSet @Param = N'@kaysayOUT bigint'
Execute sp_executesql@SQLString,@Param,@kaysayOUT = @kaysay
Select @kaysay
Return
 
GO

View 3 Replies View Related

Can Anyone Tell Me Why The Following Sql Does Not Work?

Sep 3, 2007

SELECT H.id, H.CategoryID ,H.Image ,H.StoryId ,H.Publish, H.PublishDate, H.Date ,H.Deleted ,SL.ListTitle,C.CategoryTitle
FROM HomePageImage H
JOIN shortlist SL on H.StoryId = SL.id
(INNER JOIN category C on H.CategoryId = C.CategoryId)
order by date DESC

View 4 Replies View Related

Please Help Me To Keep My Work...(:

Apr 12, 2004

Hello,

I am trying to query with my stored procedure. I am getting comma separated list as input parameter (which is VARCHAR) .

The table column, which I have to compare with input parameter value , is in INTEGER datatype.

So when , I compare Like as follows:-

" AND TABLE1.EMPID IN (@INPUTPARAMETERLIST)"

I am getting error. "Syntax error converting the varchar value '34,343' to a column of data type int."

Could anybody help me , to solve this ?

Thanks !

Nicol

View 1 Replies View Related

Why Won't This Work!?

Aug 31, 2004

I have a textbox and a checkbox on a form and I'd like to add both values to a db. The textbox value gets inserted fine but I'm having trouble with the checkbox. Any ideas would be greatly appreciated.

Thanks

Form1 is the column in my db.




SqlCommand myCmd = new SqlCommand();

myCmd.Parameters.Add("@ClientCode",SqlDbType.VarChar).Value = TextBox2.Text;

myCmd.CommandText = "UPDATE table SET Form1 = 'Yes' WHERE ClientCode = @ClientCode";


sqlConnection1.Open();
myCmd.Connection = sqlConnection1;

if( CheckBox1.Checked == true)
{
myCmd.ExecuteNonQuery();
}

sqlConnection1.Close();

View 3 Replies View Related

DBA Work

Aug 29, 2001

Hi,

Beside working right from the server how else someone can perform the SQL admistration job, I guess my question is how do most SQL DBA perform their administration without going to the server directly. Anyone --- can help please??

Thanks in advance.

View 2 Replies View Related

Does This Work?

Mar 15, 2007

Declare @StartDate datetime
Declare @EndDate Datetime
Set @StartDate = dateadd(day, datediff(day, 0, getdate()), 0)
Set @EndDate = getdate()

The job runs at 11:30 pm so I want the start date to be the same but the time to be equal to 00:00:00.0 When I run the getdate does it also return a time stamp?

The Yak Village Idiot

View 1 Replies View Related

Why Did It Work?

Aug 6, 2007

I had a problem where some users were experiencing timeouts when trying to add a single record to a table with 2.3 million records.
It's not a very wide table; only 10 columns and the biggest column in varchar 500. The rest are guid, datetime, tinyint...

There is also an old VB app that inserts about 3000 records a day into this table during office hours while users occasionally try and insert a record into this table.

Something said to me that the problem could be indexes but I wasn't quite sure because I though indexes only have an impact on select, delete & update. And not particulary on insert. But I checked it out anyway and noticed that the 3 indexes (1 column PK, 1 column Clustered & 1 column non-clustered) weren't padded. So I changed that (Fill Factor 95) and the problem has gone away. But why? I thought the insert would just have appended it to the end of the index before I made this change? Why would that time out?

View 3 Replies View Related

Why Does One Work, But Not The Other?

Mar 25, 2008



I have the following queries. The first returns the 'Unknown' row, the second works the way I would expect. Are my expectations wrong? Can someone describe for me what is going on?

Thanks




Code Snippet
select *
FROM
SynonymComFinancialCategory b
LEFT JOIN TT_FinancialCategory a
ON
a.FinanceGroup = b.FinanceGroup
AND a.FinanceCode = b.FinanceCode
AND a.Finance = b.Finance
AND b.Finance <> 'Unknown'
WHERE
a.FinanceGroup IS NULL
AND a.FinanceCode IS NULL
AND a.Finance IS NULL










Code Snippet
select *
FROM
SynonymComFinancialCategory b
LEFT JOIN TT_FinancialCategory a
ON
a.FinanceGroup = b.FinanceGroup
AND a.FinanceCode = b.FinanceCode
AND a.Finance = b.Finance
WHERE
a.FinanceGroup IS NULL
AND a.FinanceCode IS NULL
AND a.Finance IS NULL
AND b.Finance <> 'Unknown'

View 8 Replies View Related

Coalesce Does Not Seem To Work

Sep 27, 2006

  Hi,I have the following table with some sample values, I want to return the first non null value in that order. COALESCE does not seem to work for me, it does not return the 3rd record. I need to include this in my select statement. Any urgent help please.Mobile    Business     PrivateNULL        345           NULL4646        65464        65765NULL                        564654654     564           6546I want the following as my results:Number3454646564654654Select COALESCE(Mobile,Business,Private) as Number  from Table returns:3454646654654 (this is a test to see if private returns & it did with is not null but then how do i include in my select statement to show any one of the 3 fields)select mobile,business,private where private is not null returns:657655646546thanks

View 1 Replies View Related

Update Does Not Work Well

Sep 29, 2006

Hello,I created a formview in a web page. The data are in a sql server express database.With this form, I can to create a new data, I delete it but I can't to modify the data.The app_data folder is ready to write data; the datakeynames element in formview web control declared. I replace the automated query created by VS 2005 by a strored procedure to see if the problem solved.The problem is the same with an update query or a update stored procedure...Have you an idea, please.Than you for your help.Regards.

View 1 Replies View Related

Update Does Not Work

Jan 9, 2007

Im working with a detailsview and when I try to edit something and then update, the changes are not saved.
I have 2 tables ("[etpi.admin].Ocorrencias" and "[etpi.admin].SMS") that store the data that Im trying to change. Since Im having problems with the name of tables, Im coding it manually, using SQL server management studio and VWD.
I believe my code can be wrong (Im new to vwd and C# world), so here it is:
UpdateCommand="UPDATE [etpi.admin].Ocorrencias SET [Status_Ocor] = @Status_Ocor, [Percentual] = @Percentual, [IDPriori] = @IDPriori, [Abertura] = @Abertura, [IDTecRes] = @IDTecRes, [Area] = @Area, [CodEquip] = @CodEquip, [Descricao] = @Descricao, [Destinatario] = @Destinatario, [Data_Implanta] = @Data_Implanta WHERE [etpi.admin].Ocorrencias.IDOcorre = @IDOcorre
UPDATE [etpi.admin].SMS SET [idSMS] = @idSMSWHERE [etpi.admin].SMS.IDOcorre = @IDOcorre"> 
<UpdateParameters><asp:Parameter Name="idSMS" Type="Int32" /><asp:Parameter Name="Status_Ocor" Type="String" /><asp:Parameter Name="Percentual" Type="Int32" /><asp:Parameter Name="IDPriori" Type="Int32" /><asp:Parameter Name="Abertura" Type="DateTime" /><asp:Parameter Name="IDTecRes" Type="Int32" /><asp:Parameter Name="Area" Type="String" /><asp:Parameter Name="CodEquip" Type="Int32" /><asp:Parameter Name="Descricao" Type="String" /><asp:Parameter Name="Destinatario" Type="String" /><asp:Parameter Name="Data_Implanta" Type="DateTime" /><asp:Parameter Name="IDOcorre" Type="Int32" /></UpdateParameters>
Thx.

View 9 Replies View Related

My Rollback Does Not Work

May 30, 2007

My rollback does not work
In my SP I want any of cmdS,cmdS2,cmdS3,cmdS4 produces error Rollback must be executed for all of cmdS,cmdS2,cmdS3,cmdS4 . I tested for error producing situation but no rollbak occured.
How can I solve this problem. Thanks.
Below is my SP .
..........
..........
.......... 
begin transaction
..........
..........If Len(ltrim(rtrim(@cmdS)))>0
execute(@cmdS)
 If Len(ltrim(rtrim(@cmdS2)))>0
execute(@cmdS2) If Len(ltrim(rtrim(@cmdS3)))>0
execute(@cmdS3)
 If Len(ltrim(rtrim(@cmdS4)))>0
execute(@cmdS4)
If Len(ltrim(rtrim(@cmdS)))>0 or Len(ltrim(rtrim(@cmdS2)))>0 or Len(ltrim(rtrim(@cmdS3)))>0 or Len(ltrim(rtrim(@cmdS4)))>0
Beginif @@ERROR <>0
begin
rollback transaction
set @Hata = 'Error !'
end
Else
Beginset @Hata = 'Sucessfully executed :)' End
End
commit transaction
RETURN
 
 

View 1 Replies View Related

Does Not Work On Page

Jun 5, 2007

I can test it in query builder but when i preview the page and go to do the search i get nothing
Here is my statement
SELECT     Employees.Last_Name, Employees.First_Name, Job_Transaction.Name, Seq_Descript.Seq_DescriptionFROM         Call_List INNER JOIN                      Call_Group ON Call_List.Group_ID = Call_Group.Group_ID AND Call_List.Group_ID = Call_Group.Group_ID INNER JOIN                      Employees ON Call_List.Clock = Employees.Clock INNER JOIN                      Job_Transaction ON Call_Group.Group_ID = Job_Transaction.Group_ID INNER JOIN                      Seq_Descript ON Call_List.Sequence = Seq_Descript.SequenceWHERE     (Call_List.Clock = @Clock)
Mike

View 2 Replies View Related

Delete Does Not Work.

Jul 2, 2007

Hi all.I have used a SqlDataSource in my page with this delete command:DELETE FROM tblPersonnel WHERE (ID = @original_ID)and the "OldValueParameterFormatSring" property of the datasource is "original_{0}".and i also have a GridView and a button for delete in rows.(it's CommandName is "Delete"). But when i try to delete a record, the record does not get deleted and this button only makes a PostBack on the page! Why doesn't it work?
Thanks in advance.

View 8 Replies View Related

UPDATE DOES NOT WORK!!

Sep 10, 2007

hi all, i have created a gridview with the select,delete and insert commands working properly. but the update command does not work. when i edit a column and click the update button, it generates no errors but does not save the changes. it just brings back the original values. i dont know wats missing. can anyone help me?
this is part of my code:UpdateCommand="UPDATE [test101] SET Surname=@Surname, Names=@Names,Registration=@Registration,[Course code]=@Course_code,Grade=@Grade WHERE ID=@ID1 "<UpdateParameters>                <asp:Parameter Name="Surname" Type=String />                <asp:Parameter Name="Names" Type=String />                <asp:Parameter Name="Registration" Type=String />                <asp:Parameter Name="Course_code" Type=String />                <asp:Parameter Name="Grade"  Type=Int32 />                <asp:Parameter Name="ID1" Type=Int32 />            </UpdateParameters>

View 4 Replies View Related

Should This WHERE Clause Work?

Jan 16, 2008

Hi,I am having trouble with a WHERE clause:WHERE (([A] = @A) AND ([B] >= @B) AND (([C] < [D])) OR ([C] = 0 AND [D] = 0)) It's meant to only select data where A = @A, and B is more than or equal to @B, and one of the next two are true: C is less than D or C and D are both 0 Thanks,Jon 

View 3 Replies View Related

Why Would This Code Won't Work

Feb 21, 2008

I am trying to get the id of last entered record and I used select ID command but it doesn't give me the ID of last record enteredProtected Sub Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Submit.Click
Dim name, address, nice As String
Dim sConnString, sSQL, sID As String
Dim u As MembershipUsername = Me.name.Textaddress = Me.address.Text
 
u = Membership.GetUser(User.Identity.Name)
nice = u.ToString()sSQL = "INSERT into test ([Address],[Name], [username]) values ('" & _
address & "', '" & _name & "', '" & _
nice & "'); SELECT ID FROM test WHERE (ID = SCOPE_IDENTITY())"
MsgBox(sID)
MsgBox(sSQL)
sConnString = ConfigurationManager.ConnectionStrings("aspnetdbConnectionString1").ConnectionString.ToString()Using MyConnection As New System.Data.SqlClient.SqlConnection(sConnString)Dim MyCmd As New System.Data.SqlClient.SqlCommand(sSQL, MyConnection)
MyConnection.Open()
MyCmd.ExecuteNonQuery()
MyConnection.Close()
End UsingResponse.Redirect("transferred.aspx?value=2")
End Sub
End Class

View 2 Replies View Related

WHERE Clause Will Not Work

Feb 27, 2008

I am using the below WHERE clause and it will not filter out records where Companies.CompanyEmail = b@c.com
 WHERE (Companies.CompanyEmail <> 'a@a.com')  this does not work, is the @ causing a problem?  also tried 'a@a.com%' with no success.
WHERE (tblCompanies.C_CompanyEmail <> 'none')  this works fine.
Thank you
 
 

View 1 Replies View Related

My SQL Dataset Will Not Work!

May 2, 2008

For the life of me, I cant get this thing to work.. any insight would be greatly appreciated. What I'm trying to do is simply get the RealName field from my aspnetdb.Here the code.           SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=aspnetdb;Integrated Security=SSPI");                    SqlDataAdapter a = new SqlDataAdapter                    ("select RealName from dbo.aspnet_Users where UserName='Dude';", conn);                    DataSet s = new DataSet();                    a.Fill(s);                    foreach (DataRow dr in s.Tables[0].Rows)                    {                    getusersrealname.Text = (dr[0].ToString()); 

View 4 Replies View Related

Group By Won't Work??

May 30, 2008

can anyone explain why, when i do a group by clause on the following data....it has no effect?
Part          SubPart         Qty
120887     66743             83
120887     66743            100
120887     667443            25
553212     122987           119
553212     122987             67
here's my select statement:
select part, subpart sum(qty) from partdata group by part,subpart,qty
the resulting data looks identical to the original.
what i was expecting was a return of just two lines:
 
Part          SubPart         Qty
120887     66743             208
553212     122987           186
 

View 2 Replies View Related

Simple SP Won't Work, This Is Sad.

Dec 14, 2004

I am kicking myself, but cannot seem to get a simple stored procedure to return ANY records. I know it's soming that has to do with the Joins. Don't know what. I ran query analyzer and passed it a valid city and nothing was returned, but no errors either. If I run the query without any parameters, all the records are retrieved fine. ANY IDEAS?

CREATE PROCEDURE spUnitsbyCity
@city varchar
AS

SELECT A.unitcity, A.unitid, B.radioip, B.radiomac, C.videoserverip

FROM tbl_units as A

INNER JOIN tbl_radios as B ON A.unitid = B.unitid
INNER JOIN tbl_videoservers as C ON A.unitid = C.unitid

WHERE A.unitcity = @city
GO

View 2 Replies View Related

Why Won't My Sql Procedure Work?

Apr 13, 2005

Hi

For some reason my stored procedure is returning no results, when I
know it should be.  I am trying to take a textbox someone has
typed into and returning all names from the database which include that
string.  My SQL statement is

ALTER PROCEDURE getLecturerNames
(
    @lName as varchar(20)
)
AS
SELECT * FROM Lecturers
WHERE lName LIKE '%@lName%'

When I step into the procedure, the @lName parameter shows lName =
'ike' (what I typed to search) but no results are returned. 
However when I change the procedures last line  to :

WHERE lName LIKE '%ike%'

2 records are returned.  Is SQL server adding the quotation marks causing the problem, or if not what is?

View 2 Replies View Related

How To Work With Sql Parameters?

Jan 23, 2006

hi.
I am trying to use parameters in an sql statement, that runs inside a loop. every cycle I have to change the parameters values, and I'm not sure if I do it right.
I'm using the DefaultValue property like this:
SqlDataSource1.UpdateParameters["Text"].DefaultValue = txt;
is it the right way? (I had some errors when I did this, something like "value can not be truncated ")
thanks

View 1 Replies View Related

Why Does This Trigger Not Work?

Feb 28, 2006

why does this trigger not work? i'm winging this and hoping for some input. nobody's responded to my earlier posts. I get no errors, but no update either.
CREATE TRIGGER UpdateLineTotalON CartItemsFOR UPDATEASDECLARE @lineTotal Numeric(9)DECLARE @itemSell Numeric(9)DECLARE @pounds Numeric(9)SELECT * FROM CartItemsSET @lineTotal = @pounds * @itemSell

View 3 Replies View Related

Should This Insert Work?

May 17, 2006

the 1st insertcommand works but the 2nd one does not. Shouldn't I be able to substitute a var in the parameter's place?
Dim zid As String = Session("ID")
SqlDataSource2.InsertCommand = "insert into cart (lmca_nbr,office,noun, price, quantity) values (?,?,?,?,?)"
SqlDataSource2.InsertCommand = "insert into cart (lmca_nbr,office,noun, price, quantity) values (zid,?,?,?,?)"
SqlDataSource2.Insert()

View 8 Replies View Related







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