TSQL Coding Style - An Example

Jun 11, 2007

Hi!
If you like to spend some moments on my code examples,
please look at it - usage is free (-:
http://www.codeproject.com/useritems/TSQL_coding.asp

Feedback welcome.
Greetings
Bjorn

View 1 Replies


ADVERTISEMENT

Is There A Site Or A Document For Query Optimization Tips And TSQL Coding Tips?

May 9, 2008

Hi.

Me any my team are soon going to work on a performance critical application. My team has some experience of writing SQL, however we have not done performance oriented coding.

I am looking for a comphrehensive document which lists information for writing good SQL with performance. Please guide if there is such a document or web site.


Thanks,
Prasad

View 1 Replies View Related

Generic Way To Style Reports (CSS Style)

Jun 9, 2006

I want to make a CSS Style solution for my reports. I have few ideas related to this, changing the report properties on the fly, but I am not sure for which I should go for.

- We know that we can put expression on reports almost everywhere, and can also call custom code for setting up those expressions. i.e.

Public Shared Function GetValue(ByVal Key As String) As String

Dim myDataReader As SqlDataReader
Dim mySqlConnection As SqlConnection
Dim mySqlCommand As SqlCommand

mySqlConnection = New SqlConnection("server=localhost;Trusted_Connection=yes;database=tempMIQB")
mySqlCommand = New SqlCommand("SELECT * FROM [Properties] Where PropertyName='" & Key & "'", mySqlConnection)
mySqlConnection.Open()
myDataReader = mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection)

If myDataReader.Read() Then
GetValue = myDataReader.Item("PropertyValue").ToString
Else
GetValue = "None"
End If


End Function

and in textbox or any where I can say =Code.GetValue("BGColor") or from .NET dll.

For going further on with this idea I can create an .NET dll and get the list from database or XML file. (Please give suggestions for performance/scalability issue.)

- second idea is to write a custom application (script) which can go through all the reports and change the color and fonts and every thing.

- third is to use parameters and use Array.IndexOf method to search for the value, but in this case i need to add dataset to all reports and, I think we cannot access report properties i.e. Parameters from custom code, just to make a generic function to access parameter value.

View 1 Replies View Related

Equivalent Tsql For Sql Server 2000 Is Needed [from Sql Server 2005 Only Tsql]

Nov 19, 2007

Can anyone please give me the equivalent tsql for sql server 2000 for the following two queries which works fine in sql server 2005

1
-- Full Table Structure

select t.object_id, t.name as 'tablename', c.name as 'columnname', y.name as 'typename', case y.namewhen 'varchar' then convert(varchar, c.max_length)when 'decimal' then convert(varchar, c.precision) + ', ' + convert(varchar, c.scale)else ''end attrib,y.*from sys.tables t, sys.columns c, sys.types ywhere t.object_id = c.object_idand t.name not in ('sysdiagrams')and c.system_type_id = y.system_type_idand c.system_type_id = y.user_type_idorder by t.name, c.column_id


2
-- PK and Index
select t.name as 'tablename', i.name as 'indexname', c.name as 'columnname' , i.is_unique, i.is_primary_key, ic.is_descending_keyfrom sys.indexes i, sys.tables t, sys.index_columns ic, sys.columns cwhere t.object_id = i.object_idand t.object_id = ic.object_idand t.object_id = c.object_idand i.index_id = ic.index_idand c.column_id = ic.column_idand t.name not in ('sysdiagrams')order by t.name, i.index_id, ic.index_column_id

This sql is extracting some sort of the information about the structure of the sql server database[2005]
I need a sql whihc will return the same result for sql server 2000

View 1 Replies View Related

Help In Coding

Jun 23, 2006

 Dim objConn As New SqlConnection        Dim objCmd As New SqlCommand        Dim Value As String = EventCmb.SelectedItem.ToString()        objConn.ConnectionString = "Data Source=.SQLEXPRESS;AttachDbFilename='C:Documents and SettingsHPMy DocumentsVisual Studio 2005WebSitesFYP2App_DataEvent.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True"        Try            objConn.Open()            objCmd.Connection = objConn            objCmd.CommandType = CommandType.Text            objCmd.CommandText = "SELECT EventTel FROM Event WHERE (EventID = @Value)" ' See how i changed Value to @Value. This is called a Named Parameter            objCmd.Parameters.AddWithValue("@Value", Value)    ' Add the @value withthe actual value that should be put. This makes it securer            Dim RetVal As Object = objCmd.ExecuteScalar() ' This returns the First Column of the first row regardless of how much data is returned.            If Not ((RetVal Is Nothing) Or (RetVal Is DBNull.Value)) Then                ContactLbl.Text = RetVal.ToString()            Else                ' noting was returned            End If        Catch ex As Exception            Throw ex        Finally            objConn.Close()        End Try
There's an error for in line "Dim RetVal As Object = objCmd.ExecuteScalar() "
Error Message is as follow "Conversion failed when converting the nvarchar value 'LTA' to data type int."
It is due to "ExecuteScalar() " can only store int? I just need to display one data, and Value data comes form a combo box "EventCmb", which i wanted to find the selected String, compared to the "Event" database to get the "EventTel" data How do i solved this problem, any advice? Thanks!

View 1 Replies View Related

SQL Coding

Jul 2, 2002

I'm attempting to copy data from an Epicore server with multiple company
databases to another server. All this data will be placed in a single
table on the receiving server with the addition of an database identifier,
so that the receiving department will know, to which company the data
belongs. I have code that will dynamically create the SQL and then
execute it using EXEC (@SQL), and this works just fine acrosss multiple
databases. I've read in my Transact-SQL Programming book that using
EXEC() is not limited to 255 characters, but it still appears that my
dynamically created SQL is being shortened. The insert statement and the
select statement list each column, and here is that code:

SELECT @CMD = "INSERT ##APMaster(Company, timestamp, vendor_code,
pay_to_code, address_name,
short_name, addr1, addr2, addr3, addr4, addr5, addr6, addr_sort1,
addr_sort2, addr_sort3, address_type,
status_type, attention_name, attention_phone, contact_name, contact_phone,
tlx_twx, phone_1, phone_2,
tax_code, terms_code, fob_code, posting_code, location_code,
orig_zone_code, customer_code,
affiliated_vend_code, alt_vendor_code, comment_code, vend_class_code,
branch_code, pay_to_hist_flag,
item_hist_flag, credit_limit_flag, credit_limit, aging_limit_flag,
aging_limit, restock_chg_flag,
restock_chg, prc_flag, vend_acct, tax_id_num, flag_1099, exp_acct_code,
amt_max_check, lead_time,
doc_ctrl_num, one_check_flag, dup_voucher_flag, dup_amt_flag, code_1099,
user_trx_type_code, payment_code,
limit_by_home, rate_type_home, rate_type_oper, nat_cur_code,
one_cur_vendor, cash_acct_code, city, state,
postal_code, country, freight_code, url, note) SELECT '" + @DBName + "' AS
Company, timestamp, vendor_code,
pay_to_code, address_name, short_name addr1, addr2, addr3, addr4, addr5,
addr6,
addr_sort1, addr_sort2, addr_sort3, address_type, status_type,
attention_name, attention_phone, contact_name,
contact_phone, tlx_twx, phone_1, phone_2, tax_code, terms_code, fob_code,
posting_code, location_code,
orig_zone_code, customer_code, affiliated_vend_code, alt_vendor_code,
comment_code, vend_class_code,
branch_code, pay_to_hist_flag, item_hist_flag, credit_limit_flag,
credit_limit, aging_limit_flag,
aging_limit, restock_chg_flag, restock_chg, prc_flag, vend_acct,
tax_id_num, flag_1099, exp_acct_code,
amt_max_check, lead_time, doc_ctrl_num, one_check_flag, dup_voucher_flag,
dup_amt_flag, code_1099,
user_trx_type_code, payment_code, limit_by_home, rate_type_home,
rate_type_oper, nat_cur_code, one_cur_vendor,
cash_acct_code, city, state, postal_code, country, freight_code, url, note
FROM " + @DBName + "..APMaster"

Can anyone provide any insight to my problem?

TIA,
Chris

View 4 Replies View Related

Coding Help

Oct 31, 2001

Hello,

I have the following code and it seems that it is not comparing the request_close_date. What I want to do is compare the request_close_date between two tables and if it is less than the date from the TEAM3B_PULL_TOTAL_TST then insert the data into RDD_UPDATE_TST. Any help will be appreciated. It also needs to insert data into RDD_UPDATE_TST if a request exists in REQUEST_BUS_REQ and BUS_REQ_DESCRIPTION. I think that I have that coded correctly but I am not certain.

Thanks in advance,
Anne

begin
Insert into RDD_UPDATE_TST(request,business_req_id,test_case_i d,test_case_descr,request_close_date)
select distinct request,business_req_id,test_case_id,test_case as test_case_descr,request_close_date
from TEAM3B_PULL_TOTAL_TST A
where not exists (select * from BUS_REQ_DESCRIPTION_TST B where A.REQUEST = B.REQUEST)
and not exists (select * from REQUEST_BUS_REQ_TST C where A.REQUEST = C.REQUEST)
and not exists (select * from RDD_UPDATE_TST D where A.REQUEST = D.REQUEST)
and exists (select * from RDD_UPDATE_TST where REQUEST_CLOSE_DATE <>B.REQUEST_CLOSE_DATE)
end

View 1 Replies View Related

Need Help With Right Sql Coding.

Apr 28, 2003

Hi im an newbee so im not the best but try to get there some day..



CREATE TABLE table_members

(id int(11) NOT NULL auto_increment,
fornamn char(60) default NULL,
efternamn char(60) default NULL,
address char(60) default NULL,
personnr INT(11) default 0,

smeknamn char(60) default NULL,

epost char(60) default NULL, i must be a @ value in it! any ides?

kon ENUM('M','K','V') default 'M', is this right, must only be enable to type in this Alphabets sings MKV!

losenord char(60) default NULL, verlosenord char(60) default NULL,
How do i get a or fix a retype field for this losenord and verlosenord thay must be the same value to be insered in to the sql!

PRIMARY KEY (id)
UNIQUE ('smeknamn');

Any ides are good

View 1 Replies View Related

I Need ASP.Net C# Coding

Mar 12, 2007

Help me...

I need C# Language ASP.Net coding...

i've two column... One for msg another for msgLastposted


in label control view msg(last visitor)....... that msg stored in my db.

Example Table Data
---------------------------------------------
MSg|MsgLastPosed

How edit forum |2007-03-12 10:50:25.747
How to Value Change|2007-03-12 10:56:36.373
Sql Command|2007-03-12 11:00:25.047
User Control|2007-03-12 11:02:10.793
How I can uninstall|2007-03-12 13:07:51.233
-----------------------------------------------

In table have many record..

label control display msg based on last visitor time.. after that again msg
changed( based on next last visitor time).. Continue for upto first 5 record msg automatically changed..

View 1 Replies View Related

SQL CODING

Aug 28, 2007

Hi all,


I want codeing for to find (subtotal & total)the following

Input

productname qty_A_grade Qty_B_grade
abc 10 5
def 5 5
subtotal
gh 10 10
ab 10 10
Total


output

productname qty_A_grade Qty_B_grade
abc 10 5
def 5 5
subtotal 15 10
gh 10 10
ab 10 10
Total 20 20

View 3 Replies View Related

Style Sheets

Jun 24, 2005

How can I apply a style sheet "style.css" to a .rdl file (a report in Reporting Services)?
Could I modify the width of the parameters combobox?

View 1 Replies View Related

Pre-4.1-style Password

Feb 24, 2007

Hai,

" When connecting to the server with a pre-4.1 client program, use an account that still has a pre-4.1-style password. Reset the password to a pre-4.1 style for each who must use a pre-4.1 client program."

What is "pre-4.1-style password"? Can you give an example for a "pre-4.1-style password"?

View 2 Replies View Related

Format Style

Feb 21, 2008

i can't find the format style for mmddyyyy..

Funnyfrog

View 3 Replies View Related

Coding Question

Jul 25, 2006

:This is a segement of VBscript for checking lastest Backup in SQLServer 2000:
'temporary variables to useDim sTemp1Dim i, sTemp2
'read start arguments' 1 => servername' 2 => path for logfile' . => excluded databasesDim objArgsSet objArgs = WScript.ArgumentsIf objArgs.Count < 2 Then 'Not enough parameters WScript.Quit 2  end If
If the above VBScript is converted to VB.NET, how can the lines containing a boldfaced WScript be coded? What namespace in .NET should be used for that? Thanks?
 

View 3 Replies View Related

Confused. Need Some Help About SQL Coding

Jun 14, 2007

hi im a little bit confused. are the two pieces of code similar? what are the differences. i really need to know that coz i wont get access to a SQL machine until monday.


selectlastname
fromemp
wheresex = 'F' and
salary>(selectavg(salary)
fromemp
group by sex
havingsex='M')



selectlastname
fromemp
wheresex = 'F' and
salary>(selectavg(salary)
fromemp
wheresex='M')


also is it wise to use Group by and having in sub-queries?

View 2 Replies View Related

Coding In Standard SQL ?

Jul 20, 2005

Hi;Is there an **easy** way to tell tsql apart from standard sql?Will sqlserver run scripts written only in standard sql?What about variable definitions?Thanks in advanceSteve

View 8 Replies View Related

Coding Question

May 16, 2007

I am attempting to build a query that will allow me to fetch data from a table for only the last seven days. This will be used for a daily report that will need to update the day to current date every time it is run. Any help would be greatly appreciated.



Thanks

Andrew

View 2 Replies View Related

MySQL Style INSERT INTO SET

Apr 21, 2006

MySQL allowed INSERT statements that looked like this:
INSERT INTO Table SET col1 = value1, col2 = value2, col3 = value3
Basically this closely matched the format of the UPDATE statements.
Here is why this was good:  I could do something like this: if (RecordExists == false) {
SQLquery = "INSERT INTO Table SET ";
} else {
SQLquery = "UPDATE Table SET ";
}
SQLquery += "col1 = value1, ";
SQLquery += "col2 = value2, ";
SQLquery += "col3 = value3, ";
SQLquery += "col4 = value4 ";
if (RecordExists == true) {
SQLquery += "WHERE id = " + ourID;
}

If I had a good 50 columns then it means I can reuse a sizable chunk of code for both INSERT and UPDATE statements (since both use the same general format).  Whereas if I have to use "INSERT INTO Table(columns) VALUES (values)" then I'm look at duplicating a lot of code.
Does MS-SQL support something similar to "INSERT INTO SET"?  How are others dealing with this?
Thanks,
Gabe---------------------- 
 

View 6 Replies View Related

Convert Style For Datetime

Jan 19, 2006

Hi,

If the datetime value is '20.01.2006', what will be the style in CONVERT function ?

Eg : select convert(datetime, '20.01.2006') gives datetime out-of-range error.

There is no style provided for dd.mm.yyyy in SQL Server documentation. Is there any way to do such conversion with this constant value of format dd.mm.yyyy ?

Please advice,

Thanks,
MiraJ

View 4 Replies View Related

Transaction-style Inventory?

Jul 20, 2005

Hello, I'm looking for a little input on this situation.I'm working on an inventory system and was thinking that I'd like tobuild it similiar to the way a bank keeps track of your funds.If you look at at bank statement, for each line item, you'll normallysee at least date/time, description, amount (plus or minus value), andbalance.In my inventory system, the amount and balance would be a count of theitems used or transferred instead of money.Does this sound reasonable? Or is there a better design? I am planningto connect the inventory system to a few different ordering interfaces,and I think it would work well if I can dump transactions into theinventory instead of incrementing and decrementing counts.The only problem I see with this, is if I want to implement the balancepart of it with each record....I can't think of a way to do that currently.I can certainly use a trigger in the database to retrieve the mostrecent transaction and update the balance field for one record insertedat a time, but if a list of transactions is dumped into the inventorysystem at once, I'd have to compensate for that in the trigger.Ideas?*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 2 Replies View Related

Xml Input Using Xml Style Sheet

Jan 21, 2007

Trying to install SQL express but can't. I used the uninstall tool and it keeps hanging up on this error.

I am using XP and IE7.

I have also adjust my security setting to allow cross domains. Short of going and getting another machine I am at a loss.

No beta software is on machine and I also cleaned the registry..



I am not a developer. This looks like an issue all around MS..

View 1 Replies View Related

Rectangle Border Style

Apr 30, 2008



Is it possible to make a rectangle appear sunk or raised? I've had a play with the different border style settings but they don't appear to make any difference! Can anyone also tell me what the Groove, Ridge, Inset etc are supposed to do?


Thanks

View 3 Replies View Related

How To Use Border Style Expression

Dec 6, 2007

I have 2 details section in my report. I want to set bottom border style to solid for the first detail section if the second detail section is empty. And set to none if the second detail section has value. Basically I want to show the line below the first detail section and hide the second detail section if the second detail section is empty. otherwise I want to show the line only below the second detail section.

I am able to hide the detail section. But can't set the border style using expression.

I hope the above para is not confusing you

Thanks

View 6 Replies View Related

Chart Marker Style

Apr 9, 2008



Hi,

In reporting services simple chart report we can keep markers for line values like square , circle , cross etc..

My question is it possible to keep separate style marker for each line?

Thanks

Shekar Reddy

View 1 Replies View Related

Stored Procedure Coding

Nov 2, 2004

Hello,

I'm coding a stored procedure. I am creating a search function where I search multiple resultsets of data. I'm getting stuck on one part of the query, and I don't know what the best option is. Basically the query looks like this:

select * from Table where ...
and Official in (... problem area ...)

What I want is if the parameter passed in is null, return all of the valid values from the table that references this field (for example, if null is passed in, I want to pass in 'T', 'F', etc.). If the value is there, I want to pass in the value. I've been stuck on this and can't figure it out.

Any ideas? I don't want to use a dynamic query. Thanks,

Brian

View 5 Replies View Related

A Coding Challenge From The Blindman.

May 5, 2006

Hey it's not often the blindman asks for advice on sql coding (never, I think), so here is an opportunity to solve a problem I've been knocking my head against for two days.

Here is sample code for setting up the problem:create table #blindman
(pkey smallint primary key,
fkey char(1),
updateddatetime)

insert into #blindman (pkey, fkey, updated)
select1, 'A', '1/1/2006'
UNION
select2, 'B', '1/1/2006'
UNION
select3, 'A', '1/2/2006'
UNION
select4, 'B', '1/2/2006'
UNION
select5, 'A', '1/4/2006'
UNION
select6, 'B', '1/2/2006'
UNION
select7, 'A', '1/3/2006'
UNION
select8, 'B', '1/3/2006'
UNION
select9, 'A', '1/5/2006'
UNION
select10, 'B', '1/5/2006'

drop table #blindman
Notice that for fkey 'B', there are two entries with '1/2/2006', and for fkey 'A' the updated values are not in synch with the order of the primary key.
The challenge: determine the next pkey for each pkey value, ordered by [updated], and using pkey as a tie-breaker when two records have the same [updated] value.
Here is the desired output for the sample data:pkey fkey updated nextpkey
------ ---- ---------- --------
1 A 2006-01-01 3
3 A 2006-01-02 7
7 A 2006-01-03 5
5 A 2006-01-04 9
2 B 2006-01-01 4
4 B 2006-01-02 6
6 B 2006-01-02 8
8 B 2006-01-03 10
Records 9 and 10 are missing because they have not succeeding records, though I'd be just has satisfied to include them with NULL as their nextpkey value.
Ideally, I want this as a VIEW.

Who's up for the challenge?

View 14 Replies View Related

Beginner's Question To Coding

Oct 10, 2006

ok this is for a class assignment so if anyone doesnt want to help thats cool, but its just a small extra credit assignment and we havent gone over it in class and and the book, well is confusing to say the least so here are my questions:

What is the total weight of different colored parts?

ok so i have a parts table, with pcolor and pweight in it but i am unsure how to code that, here is kinda what i think it might be, i have no real way to check to see if it is correct though:

Select sum pweight
from parts
where distinct pcolor

looks horribly wrong so any help is appreciated. here is another one:

What colored part has total weight greater than 8 units?

select pcolor
from parts
where sum pweight > 8

???
i dunno lol.

there is a hint that says to use "GROUP BY" and "HAVING" but i dont see how that fits in... any ideas?

View 2 Replies View Related

Grant Permissions Through Coding

Nov 14, 2006

Hello

Is it possible to grant permissions like SELECT,INSERT,DELETE permissions to a database in SQL Server 2005 as we give it through SQL Server Management Studio.

Is it possible to grant permissions without specifying the username,passwd

Thanks In Advance
Poornima

View 16 Replies View Related

Confusing SQL Date Coding

Jun 22, 2007

I am new to MS SQL coding and I am having a problem with date conversions. In PL/SQL, I could convert numeric months into character months in their own columns by using the DECODE function. An example would be:

DECODE(to_char(M.My_Table, 'MM'),
'04', 'Apr', '05', 'May', '06', 'Jun', '07',
'Jul', '08', 'Aug', '09', 'Sep', '10', 'Oct',
'11', 'Nov', '12', 'Dec', '01', 'Jan', '02',
'Feb', '03', 'Mar'),
DECODE(to_char(M.My_Table, 'MM'),
'04', 'Q1', '05', 'Q1', '06', 'Q1',
'07', 'Q2', '08', 'Q2', '09', 'Q2',
'10', 'Q3', '11', 'Q3', '12', 'Q3',
'01', 'Q4', '02', 'Q4', '03', 'Q4'),

How does one convert something like this in MS SQL?

View 15 Replies View Related

SQL - How To - I Need A Query Solution, No Coding....

Nov 1, 2007

Hi. I'm looking at a problem and I can't find any solution short ofcoding.I have a pool of, say, 1000 PINS. I have 7 tables (buckets). Any ofthe 1000 PINS can be in 0, 1, 2, or... or all 7 buckets. So let's saythat-bucket A has 100 PINS-bucket B has 300 PINS-bucket C has 600 PINS-bucket D has 200 PINS-bucket E has 500 PINS-bucket F has 350 PINS-bucket G has 700 PINSI need to know, for each PIN, the number of buckets (tables) itbelongs to, and which ones, i.e:- PIN 1 belongs to A, C, D, so it belongs to 3 buckets- PIN 2 belongs to A, C, D, F, so it belongs to 4 buckets- PIN 3 belongs to A, so it belongs to 1 bucket- PIN 4 belongs to A, B, C, D, G, so it belongs to 5 buckets- PIN 5 belongs to ..., so it belongs to 0 bucketsetc, etcWhat would be the simplest way to achieve that, please ?Thank you very muchAlex.

View 5 Replies View Related

UTF-8 Coding Of MSSQL 2005 DB

Mar 26, 2008

Hi List,I am searching franticly for a solution (or the procedure) to settingthe coding of a new DB to UTF-8. I can find no setting in the ServerManager, during creation of the DB, to influence this. Can someoneplease show me the way? Thanks--Shawn

View 3 Replies View Related

SSIS Versus Coding.

Jun 25, 2007

This question probably overlaps a few different topic areas.



As I will be required to work with both Oracle and SQL Server I will be in a difficult position with SSIS(due to it's change in distribution).



Therefore I am having to look at alternatives.



With coding a can open a text file and parse it reasonably to my satisfaction. However getting the data into the database is incredibly slow.



I am using an Insert into for each line, which I am sure everone will shake their head over. This seems to be pretty slow even using transactions.



Is there any scope in using data tables or have the read on one thread and write on another.



Other than that is there an Oracle equivalent of SSIS which comes (probably get shot for asking that on a microsoft web site, but would probably get shot if I asked on Oracle forums as well).



In the past we had reasonable results in outputting to csv and then doing some sort of bulk insert, messy and irritating though this may be.



Any ideas on this area will be gratefully accepted.

View 2 Replies View Related

Is There Any Way To Insert Image Into DB Without Coding ??

May 25, 2007

I need just testing function that retreive image from SQL SERVER 2005 with data type "image" so i need to know another way to insert image into SQL SERVER2005 without coding. Because In MICROSOFT ACCESS, I just copy image and then, paste into column.

View 3 Replies View Related







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