I have Table called performance where i what to get the AsOfDate(char 10) from that table... and i want to get the most recent based on this function.
ALTER FUNCTION [dbo].[udf_Quarter] (@Date datetime)
RETURNS char(10)
AS
BEGIN
DECLARE @month int
SET @month = Month(@Date)
RETURN
CASE
WHEN @month BETWEEN 4 AND 6 THEN 5
WHEN @month BETWEEN 7 AND 10 THEN 6
WHEN @month BETWEEN 11 AND 12 THEN 7
WHEN @month BETWEEN 1 AND 3 THEN 8
END
END
and i want this to return 3/31/2008 but i want to make it dynamic like if it is "3/31' and year can be depending on the year it passes
I debug SPS on a daily basis and I use SQL profiler to help me trace where the problem is. Once I have established which SP is the main problem I need to debug the line of code.
What I do is Cut and Paste the SQL Profiler details and populate all the parameters,sometimes that can be 30 and more..
Now what i thought is to write an SP or Function where I pass :
SP name and Parameters that profiler genererates and returns me Declare Statements and Set Statements with parameters filled.
EG
Profiler Returns Customer_INSERT,20,'JO',BLOGG','5 LONDON ROAD'
I would call my new SP =PopulateSPParams and cut and paste the profiler's string PopulateSPParams 'Customer_Insert,20,'JO',BLOGG','5 LONDON ROAD'
this will RETURN THE FOLLOWING THAT WILL IMMENSILY HELP MY DAILY PROGRAMMING.
Hi i am not sure as u which forum to post but.. i wanted to write a stored procedure and i am stuck as to how to get the data.I have written some which i will post it below but i am not sure how should i go ahead.. These are tables...
I have a table called SourceDBF Which has the following Fields...
The relationship between the 2 tables is in PLAN_NUM and if the Source_Id = 1 i need to pull SRC1NAME , If 2 - SRC2Name and so forth..
I want to write a query that will find SOURCE_ID thats been listed in the SourceDBf table but that dont have a SRCNAME to it.. and this is my query to get the corresponding name for the SOURCE_ID and it works fine
Code Block Select Distinct @ClientId, SOURCE_NUM, (Select CASE s.SOURCE_NUM When 1 Then SRC1NAME WHEN 2 Then SRC2NAME WHEN 3 THEN SRC3NAME WHEN 4 THEN SRC4NAME WHEN 5 THEN SRC5NAME WHEN 6 THEN SRC6NAME WHEN 7 THEN SRC7NAME WHEN 8 THEN SRC8NAME WHEN 9 THEN SRC9NAME WHEN 10 THEN SRC10NAME WHEN 11 THEN SRC11NAME WHEN 12 THEN SRC12NAME WHEN 13 THEN SRC13NAME WHEN 14 THEN SRC14NAME WHEN 15 THEN SRC15NAME END FROM PlanDBF p Where p.PLAN_NUM = s.PLAN_NUM ) as SourceName FROM SourceDBF s
But when i try to join query with this query it doesnt work
Code Block SELECT RowNumber, 'Source.Dbf, Plan.Dbf', 'Source Name is missing for Source Number "' + IsNull(RTrim(f.SOURCE_NUM),'Unknown') + '" in Plan.Dbf table.' FROM SourceDbf f
I am trying to get SOURCE_ID which do not hae a SRCName.
Hi, I need to write a simple function to format the contents of the fields in my table. I bascially want to say that if the value in a field is below '0' then format the text in colour red and if the value in the field is 0 or above then format it in black. Obviously this can be done by writing an expression in each field but i would prefer to write a function - any ideas.....
I would like to write a user defined function that takes as an input a varchar and returns an xml. If the string is valid xml the function would just return it. If the string is not valid xml then the function would encode the value before returning it.
The function would look something like this:
Code Snippet
CREATE FUNCTION dbo.EncodeXMLIfNotValid (
@InputString varchar(max)
)
RETURNS xml
AS
BEGIN
DECLARE @xml xml
BEGIN TRY
SET @xml = CAST(@InputString as xml)
END TRY
BEGIN CATCH
SET @xml = '<![CDATA[' + @InputString + '>]]>'
END CATCH
RETURN( @xml )
END
However, after writting this I figured out that using BEGIN TRY and CATCH is not allowed in a UDF.
Any thoughts or ideas how I could write a function with this behavior?
I have a table with a column called Userdef. I is a user defined field. It looks like this ;;Polk;D-0002;;;;As you can see it is delimited by semicolons. I need to separate the semicolons into separate files like this Field1Field2Field2Field4Field5Field6<null><null>Polk<null>D-0002<null>How do I write this query in SQL Server?
Hello all. I have an Access table with EmpName, JobTask, and Hours. Multiple lines can contain the same Employee with the same JobTask. What I need to do is to list the Employee, JobTasks (grouped), and summed hours for each JobTask.
DB Ex:
John Doe Welding 8 John Doe Cleaning 4 Bubba Smith Fork Lift 3 John Doe Welding 7 Steve Johnson Welding 5 Bubba Smith Fork Lift 6
Page output:
John Doe Welding 15 hrs. Cleaning 4 hrs.
Bubba Smith Fork Lift 9 hrs.
Steve Johnson Welding 5 hrs.
This is how I figured it should be, but it's not working for me:
SELECT EmpName, SUM (Hours), JobTask FROM tblEmpTime Group By JobTask
suppose,the type of the stored procedure's paramters is varchar .I hate to add parameterNames and types.If i can read the string of the stored procedure the get the paramterNames by operating text? public void storeOperate(string stringParameter,string name) { string[] strs=stringParameter.Split('&'); SqlConnection conn = new SqlConnection(getConnectionString.getconnectionString()); SqlCommand cmd=new SqlCommand(name,conn); cmd.CommandText=name; cmd.CommandType=CommandType.StoredProcedure; foreach(string str in strs) { cmd.Parameters.Add(".....",SqlDbType........).Value=str; //my trouble } conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); cmd.Dispose(); }
Hi Experts,I am working on SSRS 2005, and I am facing a problem in counting theno of days.My database has many fields but here I am using only two fieldsThey are Placement_Date and Discharge_DateIf child is not descharged then Discharge_Date field is empty.I am writing below query to count the number of days but is is notworking it is showing the error"The conversion of a char data type to a datetime data type resultedin an out-of-range datetime value."select casewhen convert(datetime,Discharge_Date,103) = '' thendatediff(day,CONVERT(datetime,Placement_Date,103), GETDATE())elsedatediff(day,CONVERT(datetime,Placement_Date,103),CONVERT(datetime,Discharge_Date,103))end NoOfDaysfrom Placement_DetailsSo please tell me where I am wrong?Any help will be appriciated.RegardsDinesh
I'm working on Application that requires me to check and display status of reports running on report server. My application calling ListJobs() function of Job class part of Reporting Services Web Service API. When i run my application i'm getting insufficient previleges error. So i need to find out what type of permission i need to excute ListJobs().
This is very important part of my app. Please help me out.
I have this function in access I need to be able to use in ms sql. Having problems trying to get it to work. The function gets rid of the leading zeros if the field being past dosn't have any non number characters.For example:TrimZero("000000001023") > "1023"TrimZero("E1025") > "E1025"TrimZero("000000021021") > "21021"TrimZero("R5545") > "R5545"Here is the function that works in access:Public Function TrimZero(strField As Variant) As String Dim strReturn As String If IsNull(strField) = True Then strReturn = "" Else strReturn = strField Do While Left(strReturn, 1) = "0" strReturn = Mid(strReturn, 2) Loop End If TrimZero = strReturnEnd Function
I have some experience with MS SQL mostly installation, configuration, maintaining, etc. But I am trying to teach myself some TSQL. I have bought a few beginner books and have some test machines. In advance, I appreciate any feedback!
I have a database with two tables. I want to calc the min salary for a class of employees. The "wage" is in one table and the "status" is in another.
USE Database GO SELECT MIN(Wage) AS "Min Salary", Status FROM Employee, Job WHERE Status = '1' GROUP BY Wage, Status GO
The result set brings back all not the "status" class that I want.
I wrote a stored procedure in SQL 2K5, and I would like to write to the sql log without using a rasieerror function. I just would like to log the sucessfull steps without exiting the proc. I am not sure how to do this. Any help would be appreciated.
I am following the: Lesson 8: Obtaining Data from a SQL Server 2005 Express Edition Database video series. I cannot get the following to write changes to the SQL Database:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
I do get the message box to popup showing 1 row of changes when I make one change, however that change does not get written to the database. Is this enough info to have any idea why?
I was hoping that someone might be able to help a SQL statement for this, if possible. I have two tables, InvoiceDetails and InvoiceLineItems. What I'd like to do is write a query that will return all invoices, but also return a value InvoiceTotal Based on SUM(InvoiceLineItems.qty * InvoiceLineItems.unitPrice). I've tried a few different methods of writing this, but haven't had much luck. Can anyone shed some light on this for me? Thanks.
Hi.I realize this may have been asked a thousand times before, but it's still not working for me. I would appreciate any help with it. First, I created a GridView, and from it I created a new SqlDataSource and let it point to the database in C:My ProjectApp_DataASPNETDB.MDF. This automatically created a connectionString in the Web.Config file, saying the following: "R1ASPNETDBConnectionString" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename="C:My ProjectApp_DataASPNETDB.MDF";Integrated Security=True;Connect Timeout=30;User Instance=True" providerName="System.Data.SqlClient" /> Now when I try to programatically use that connection string, the program crashes. Below is my code: <script runat="server"> String sqlConnectionString = @"Data Source=.SQLEXPRESS;AttachDbFilename="C:My ProjectApp_DataASPNETDB.MDF";Integrated Security=True;Connect Timeout=30;User Instance=True";
protected void Page_Load(object sender, EventArgs e) { using (SqlConnection conn = new SqlConnection(sqlConnectionString)) { conn.Open(); const String selectQuery = "SELECT StatusName FROM Status ORDER BY StatusName"; Label1.Text = ""; using (SqlCommand cmd = new SqlCommand(selectQuery, conn)) { SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { Label1.Text += dr[0]; while (dr.Read()) { Label1.Text += ", "; Label1.Text += dr[0]; } Label1.Text += ". "; } else Label1.Text = "None."; } if (conn != null) conn.Close(); } } Here's the error message I'm getting: Server Error in '/My Project' Application.
Keyword not supported: 'c:my projectapp_dataaspnetdb.mdf";integrated security'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Keyword not supported: 'c:my projectapp_dataaspnetdb.mdf";integrated security'.
Source Error:
Line 15: protected void Page_Load(object sender, EventArgs e)Line 16: {Line 17: using (SqlConnection conn = new SqlConnection(sqlConnectionString))Line 18: {Line 19: conn.Open();
Source File: c:My Project est.aspx Line: 17
Stack Trace:
[ArgumentException: Keyword not supported: 'c:my projectapp_dataaspnetdb.mdf";integrated security'.] System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +417 System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +99 System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +52 System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +25 System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +141 System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value) +38 System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +4 System.Data.SqlClient.SqlConnection..ctor(String connectionString) +21 ASP.test_aspx.Page_Load(Object sender, EventArgs e) in c:My Project est.aspx:17 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +45 System.Web.UI.Control.OnLoad(EventArgs e) +80 System.Web.UI.Control.LoadRecursive() +49 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3745 My question is: How should I write the connection string? I have a feeling the problem is with the quotes ("), but I can't figure out how to write it otherwise.Thank you very much.
Hello, I have two tables: Customer Training Requests has say two columns.Customer - Class Requested a 1b 1c 1a 2b 2c 3a 3 I have another table called packages, which has packages of class.Package No. Class1 11 2 I want to write a query which will return only those customers who have requested exactly the classes in a particular package.so in above example if the package is 1 the query should return only customer b as only customer b has requested class 1 and 2. Any suggestions? Thanks,Paresh.
Hello, how can do the following using sql: if exists(select * from siteindex where site_url like '%msn.com')ThenUpdate siteindex Set dmodified = GetDate(), isFullPage = 0, fp_flname = 'filename', fp_iWidth = 800, fp_iheight = 600 Where site_url = '%msn.com' else insert into siteindex (site_url, dcreated, dmodified, isFullPage, fp_flname, fp_iWidth, fp_iHeight) Values ('msn.com', GetDate(), GetDate(), 0, 'filename', 800, 600) I cant get the syntax right. Thanks!
Hi all, I have a problem with retrieving data from lookup tables. Ok here is the issue I have a Tables ... Tables | Schools StuAccount Fields | Sch_Id (pk) Student_ID (pk) School_Name AccountableSch_Id DistrictName TestedSch_Id ParticipatedSch_Id Ok, so i have two tables Schools and StuAccount, each has one primary key and and the StuAccount has three foreign keys that associates to the Schools TABLE which has a the definition of school names wich i want to retrieve for all three foreign key in the stuaccount table. Here is what i want .... Student_ID AccountableSch_Id Shool_Name( this the name of the AccountableSch_Id ) TestedSch_Id Shool_Name( this the name of the TestedSch_Id) ParticipatedSch_Id Shool_Name( this the name of the ParticipatedSch_Id) I just want to look up the id and put the school name in the final resulting join and i have no idea how to lookup the table School three time and put school name for all three foreign keys.?? Any help will be much appreciated. Thanks
Please find the necessary SQL scripts to generate a small version of my database and some data at the bottom of this post.
Here's a short description of what the database is all about: It's a project tracking and management system. Contracts go into the tblDeals table. Because each project may be different in nature, project phases are defined in tblPhaseType and tblPhase tables. The table used to keep track of what's going on is the tblProduction table.
Here's what I need to do. When a project is completed -- meaning it has gone through all the phases that it needs to go through -- I want a trigger to fire up and change the contract status in the tblDeals table to "Completed" whose value is 1. When a new contract gets entered into the table, the Contract Status is set to 5 by default which means "In Progress" -- as defined in tblContractStatus. The tricky part is that because, each project is different and has different number of phases, the trigger has to make sure that all the phases have been submitted into the tblProduction table for that particular deal.
I'd really appreciate some help here. Thanks in advance for all your help.
--------------------------------------- Here's the script ---------------------------------------
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblDeals_tblCompany]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[tblDeals] DROP CONSTRAINT FK_tblDeals_tblCompany GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblDeals_tblContractStatus]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[tblDeals] DROP CONSTRAINT FK_tblDeals_tblContractStatus GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblDeals_tblPhaseType]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[tblDeals] DROP CONSTRAINT FK_tblDeals_tblPhaseType GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblPhase_tblPhaseType]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[tblPhase] DROP CONSTRAINT FK_tblPhase_tblPhaseType GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblProduction_tblDeals]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[tblProduction] DROP CONSTRAINT FK_tblProduction_tblDeals GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblProduction_tblPhase]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[tblProduction] DROP CONSTRAINT FK_tblProduction_tblPhase GO
/****** Object: Table [dbo].[tblProduction] Script Date: 11/20/2003 11:30:48 AM ******/ if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblProduction]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[tblProduction] GO
/****** Object: Table [dbo].[tblDeals] Script Date: 11/20/2003 11:30:48 AM ******/ if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblDeals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[tblDeals] GO
/****** Object: Table [dbo].[tblPhase] Script Date: 11/20/2003 11:30:48 AM ******/ if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblPhase]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[tblPhase] GO
/****** Object: Table [dbo].[tblCompany] Script Date: 11/20/2003 11:30:48 AM ******/ if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblCompany]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[tblCompany] GO
/****** Object: Table [dbo].[tblContractStatus] Script Date: 11/20/2003 11:30:48 AM ******/ if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblContractStatus]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[tblContractStatus] GO
/****** Object: Table [dbo].[tblPhaseType] Script Date: 11/20/2003 11:30:48 AM ******/ if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblPhaseType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[tblPhaseType] GO
/****** Object: Table [dbo].[tblCompany] Script Date: 11/20/2003 11:30:50 AM ******/ CREATE TABLE [dbo].[tblCompany] ( [CompanyID] [int] IDENTITY (1, 1) NOT NULL , [CompanyName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY] GO
/****** Object: Table [dbo].[tblContractStatus] Script Date: 11/20/2003 11:30:50 AM ******/ CREATE TABLE [dbo].[tblContractStatus] ( [StatusID] [tinyint] IDENTITY (1, 1) NOT NULL , [Status] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY] GO
/****** Object: Table [dbo].[tblPhaseType] Script Date: 11/20/2003 11:30:51 AM ******/ CREATE TABLE [dbo].[tblPhaseType] ( [PhaseTypeID] [tinyint] IDENTITY (1, 1) NOT NULL , [Desription] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY] GO
/****** Object: Table [dbo].[tblDeals] Script Date: 11/20/2003 11:30:51 AM ******/ CREATE TABLE [dbo].[tblDeals] ( [DealID] [int] IDENTITY (1, 1) NOT NULL , [CompanyID] [int] NOT NULL , [DealDate] [smalldatetime] NOT NULL , [PhaseTypeID] [tinyint] NOT NULL , [CashAmount] [smallmoney] NOT NULL , [StatusID] [tinyint] NOT NULL ) ON [PRIMARY] GO
/****** Object: Table [dbo].[tblPhase] Script Date: 11/20/2003 11:30:52 AM ******/ CREATE TABLE [dbo].[tblPhase] ( [PhaseID] [tinyint] IDENTITY (1, 1) NOT NULL , [PhaseTypeID] [tinyint] NOT NULL , [PhaseDescription] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [PhasePercentage] [float] NOT NULL ) ON [PRIMARY] GO
/****** Object: Table [dbo].[tblProduction] Script Date: 11/20/2003 11:30:52 AM ******/ CREATE TABLE [dbo].[tblProduction] ( [TransactionID] [int] IDENTITY (1, 1) NOT NULL , [DealID] [int] NOT NULL , [PhaseID] [tinyint] NOT NULL , [TransactionTimeStamp] [smalldatetime] NOT NULL , [Comments] [varchar] (150) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) ON [PRIMARY] GO
ALTER TABLE [dbo].[tblCompany] WITH NOCHECK ADD CONSTRAINT [PK_tblCompany] PRIMARY KEY CLUSTERED ( [CompanyID] ) ON [PRIMARY] GO
ALTER TABLE [dbo].[tblContractStatus] WITH NOCHECK ADD CONSTRAINT [PK_tblContractStatus] PRIMARY KEY CLUSTERED ( [StatusID] ) ON [PRIMARY] GO
ALTER TABLE [dbo].[tblPhaseType] WITH NOCHECK ADD CONSTRAINT [PK_tblPhaseType] PRIMARY KEY CLUSTERED ( [PhaseTypeID] ) ON [PRIMARY] GO
ALTER TABLE [dbo].[tblDeals] WITH NOCHECK ADD CONSTRAINT [PK_tblDeals] PRIMARY KEY CLUSTERED ( [DealID] ) ON [PRIMARY] GO
ALTER TABLE [dbo].[tblPhase] WITH NOCHECK ADD CONSTRAINT [PK_tblPhase] PRIMARY KEY CLUSTERED ( [PhaseID] ) ON [PRIMARY] GO
ALTER TABLE [dbo].[tblProduction] WITH NOCHECK ADD CONSTRAINT [PK_tblProduction] PRIMARY KEY CLUSTERED ( [TransactionID] ) ON [PRIMARY] GO
ALTER TABLE [dbo].[tblDeals] ADD CONSTRAINT [DF_tblDeals_StatusID] DEFAULT (5) FOR [StatusID] GO
ALTER TABLE [dbo].[tblProduction] ADD CONSTRAINT [DF_tblProduction_TransactionTimeStamp] DEFAULT (getdate()) FOR [TransactionTimeStamp] GO
exec sp_addextendedproperty N'MS_Description', N'Determines the type of phase structure this deal will go through', N'user', N'dbo', N'table', N'tblDeals', N'column', N'PhaseTypeID' GO exec sp_addextendedproperty N'MS_Description', N'Identifies the current status of deal', N'user', N'dbo', N'table', N'tblDeals', N'column', N'StatusID'
GO
exec sp_addextendedproperty N'MS_Description', N'Determines the percentage value of the phase', N'user', N'dbo', N'table', N'tblPhase', N'column', N'PhasePercentage'
--------------------------------------- And here's some data ---------------------------------------
INSERT INTO [tblPhaseType] ([Desription])VALUES('TV Commercial - 4 Phases') INSERT INTO [tblPhaseType] ([Desription])VALUES('Full Campaign - 6 Phases')
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(1,'Customer Info',1.500000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(1,'Write script',2.500000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(1,'Shoot',3.500000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(1,'Edit commercial',2.500000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Customer info',1.500000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Write script',1.500000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Design print ad',1.500000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Shoot',1.500000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Edit',2.000000000000000e-001) INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Publish',2.000000000000000e-001)
INSERT INTO [tblContractStatus] ([Status])VALUES('Completed') INSERT INTO [tblContractStatus] ([Status])VALUES('Hold') INSERT INTO [tblContractStatus] ([Status])VALUES('Collections') INSERT INTO [tblContractStatus] ([Status])VALUES('Legal') INSERT INTO [tblContractStatus] ([Status])VALUES('In Progress')
INSERT INTO [tblCompany] ([CompanyName])VALUES('Johnny''s Remodeling') INSERT INTO [tblCompany] ([CompanyName])VALUES('Perfect Cut Lawncare') INSERT INTO [tblCompany] ([CompanyName])VALUES('Useless Ideas Unlimited') INSERT INTO [tblCompany] ([CompanyName])VALUES('Try-It-Again, Inc.')
INSERT INTO [tblDeals] ([CompanyID],[DealDate],[PhaseTypeID],[CashAmount],[StatusID])VALUES(1,'Aug 5 2003 12:00:00:000AM',1,120.0000,5) INSERT INTO [tblDeals] ([CompanyID],[DealDate],[PhaseTypeID],[CashAmount],[StatusID])VALUES(2,'Sep 9 2003 12:00:00:000AM',2,150.0000,5) INSERT INTO [tblDeals] ([CompanyID],[DealDate],[PhaseTypeID],[CashAmount],[StatusID])VALUES(3,'Sep 10 2003 12:00:00:000AM',2,130.0000,5) INSERT INTO [tblDeals] ([CompanyID],[DealDate],[PhaseTypeID],[CashAmount],[StatusID])VALUES(4,'Nov 20 2003 12:00:00:000AM',1,190.0000,5)
INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(1,1,'Nov 10 2003 10:23:00:000AM','Received company logo') INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(1,2,'Nov 10 2003 10:23:00:000AM','Finished writing script') INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(2,5,'Nov 10 2003 10:23:00:000AM','Just received company info') INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(2,7,'Nov 10 2003 10:24:00:000AM','Finished designing ad copy') INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(1,3,'Nov 20 2003 11:29:00:000AM','Did more work') INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(1,4,'Nov 20 2003 11:29:00:000AM','Finally finished the job')
i have a query and i would like to write the contents of the dataset out directly to a file and not bother with creating another temp table and then exporting it with a command with a dts to a csv file.
it is a type of reporting that i am trying to do but i just need to export the raw data i retreive from the query
Is it possible to do the following without cursors or creating an identity column:
I have a table from legacy data with ~ 1 million records. I need to insert this into the new table which has a unique varchar(11) key. For the new system this key is generated by calling a SP that returns the next key in sequence. To put the legacy data records in the same table I want to first create a new column at end of legacy data table and populate this using SQL without going thru using cursor and calling the SP for each and every record to get a unique varchar(11) key.
I have a table that has records that have multiple entries with only a slight varitation to accomodate client needs. I want to filter out the duplicates and call only one record row. How can I do this type of thing and make it work; example - SELECT * FROM clients WHERE client_id DISTINCT I know that is not correct but that is what I need. I need to get all the columns but only one record for each client using the client_id field as the source of information.????
please help me write a query: I have a user function dbo.udf_Valid which is return true or false (@SID ,@PType,@Group,@Date)
Table 1 with this info: SID PType Group 12 12 123 45 1 456
Table2 with this info: PType PType2 12 13 12 45 12 8 1 8 1 9
when I pass the data from table1 to the function I am Okay. The complexity starts when table2 is involved. I need to pass PType2 to the function if Ptype is exists in table1. If function returns true for one of the PType2 return true in all other cases false.
I need to be able to filter out duplicates that have different values in a particular field.
For example, I have a table that contains the following:
Code:
WBS1 WBS2 WBS3 Amount Section 123 13 00 475 F 123 13 00 0 L 123 21 01 125 C 123 24 03 50 L
I need to filter out the first two lines because they have the same values for the first three columns but the last column under 'Section' has different values.
Hello I'm new on sql server and I wonder if there's an specific order for writing a query's clauses (joins, and other conditions in where clause or even the order of the tables in the from clause), I mean, I have a query that takes 1 minute executing, but if I execute the same query after moving the tables in the from clause (changing the order) It takes 5 seconds, could you please tell me Why ??? and what's the best order from writing a query ?
This is the query I was talking about:
SELECT TREP_VALOR_PRECIOS.CDPRECIO, TREP_VALOR_PRECIOS.NMANO, TREP_VALOR_PRECIOS.NMSEMANA, ISNULL(DBO.FNCREP_VALORPRECIO(TREP_PRECIOS.CDPRECI O,0,TREP_VALOR_PRECIOS.NMSEMANA,TREP_VALOR_PRECIOS .NMANO),0) VRPAGO_COBRO, UN_TASASCAMBI.TASTASACAMB VRTASA_CAMBIO, TREP_PRECIOS.CDTIPO_PRECIO, TREP_VALOR_PRECIOS.SNACTIVO, 'N' SNACTIVAR FROM UN_TASASCAMBI, -- I just moved this one to the end of the from clause T2_CALENDARIO, -- I just moved this one to the end of the from clause UN_MONEDEXTRA, TREP_PRECIOS TREP_PRECIOS_BASE, TREP_VALOR_PRECIOS, TREP_PRECIOS WHERE T2_CALENDARIO.CALFECHAINICIAL BETWEEN UN_TASASCAMBI.TASFECHDESD AND UN_TASASCAMBI.TASFECHHAST AND UN_TASASCAMBI.TASCOMPANIA = UN_MONEDEXTRA.MEXCOMPANIA AND UN_TASASCAMBI.TASMONECAMB = UN_MONEDEXTRA.MEXCODIGO AND T2_CALENDARIO.CALSEMANA = TREP_VALOR_PRECIOS.NMSEMANA AND T2_CALENDARIO.CALANO = TREP_VALOR_PRECIOS.NMANO AND T2_CALENDARIO.CALTIPOFRUTA = '01' AND UN_MONEDEXTRA.MEXCOMPANIA = TREP_PRECIOS_BASE.CDCOMPANIA AND UN_MONEDEXTRA.MEXCODIGO = TREP_PRECIOS_BASE.CDMONEDA AND TREP_PRECIOS_BASE.CDMONEDA <> 'PESOC' AND TREP_PRECIOS_BASE.CDPRECIO = TREP_VALOR_PRECIOS.CDPRECIO AND TREP_VALOR_PRECIOS.SNACTIVO = 'S' AND TREP_VALOR_PRECIOS.CDPRECIO = DBO.FNCREP_OBTENER_PRECIO_BASE(TREP_PRECIOS.CDPREC IO) AND TREP_PRECIOS.CDTIPO_PRECIO = 'F'
Now, I want search for records with employee id 1 in a way that if column emp1 contains 1 then I want the data in column emp2, and if column emp2 contains 1, then I want data in column emp1.
The output has to be a single column with no duplicate values. In the above example, for employee id 1, the output would be, 2,5 and 6 only.
This table has lakhs of records. I have to scan both columns for a given employee id. What will be the most optimized way to retrieve the data faster. Also, do I need to restructure this table for faster data retrieval? I have indexes on emp1 and emp2 columns. Do we need union here and if yes, what is the best optimized query for the same?