CASE field_val
WHEN 'M5' THEN EXEC ( @query)
ELSE THEN print ''
END
I have a SP , and i state a query .. but i only
want this query to be executed based on the value
of field_val , otherwise i print a blank ..
but when i check the syntax (ms sql server 2000)
i get "invalid syntax near CASE ..
The error is 'Server: Msg 170, Level 15, State 1, Procedure sp_append_SQLtables_to_NewDB_V2, Line 13 Line 13: Incorrect syntax near '.dbo.rt_action_level_type'.'
Hello DBA's i use this proc to insert & update the records in the databse update works good untill i change the user id. userid can be changed where adminuserid is the IDENTITY coulmn in the table.ALTER PROCEDURE [dbo].[spinsertusers] -- Add the parameters for the stored procedure here @adminuserid varchar(36), @userid varchar(15), @fname varchar(25), @mname varchar(25), @lname varchar(25), @password varchar(15), @address1 varchar(255), @address2 varchar(255), @postcode varchar(15), @cityidentity varchar(36), @dob smalldatetime , @email varchar(50), @crtduser varchar(36), @crtdon datetime, @isactive char(4), @mode char(10), @reccount INT output AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @Count INT -- Insert statements for procedure here IF (@mode='insert') SET @Count=(SELECT COUNT(*) FROM adminusermaster WHERE userid=@userid) IF @count=0 --Inserting the Records BEGIN INSERT INTO [school].[dbo].[AdminUserMaster] ([AdminUserIdentity] ,[FirstName] ,[MiddleName] ,[LastName] ,[UserID] ,[Password] ,[Address1] ,[Address2] ,[PostCode] ,[CityIdentity] ,[DOB] , ,[CreatedBy] ,[CreatedOn] ,[IsActive]) VALUES ( @adminuserid , @fname , @mname , @lname , @userid , @password, @address1, @address2, @postcode, @cityidentity , @dob, @email, @crtduser, @crtdon , @isactive ) SET @reccount=2 return @reccount END
-- End of Query IF (@mode='update')
SET @Count=(SELECT COUNT(*) FROM adminusermaster WHERE userid=@userid) IF @Count=1 --Query for Update the Records BEGIN update AdminUserMaster set [FirstName]=@fname , [MiddleName] =@mname, [LastName]=@lname, [userid]=@userid , [Address1]=@address1, [Address2]=@address2, [PostCode]=@postcode, [CityIdentity]=@cityidentity, [DOB]=@dob, =@email, ModifiedBy=@crtduser , ModifiedOn=@crtdon , isactive='Y' where AdminUserIdentity= @adminuserid set @reccount=3 return @reccount END
I am not an expert with sp. I am trying to pass the column name as a parameter but I get the following error "Must declare the variable '@strColumnName'."
ALTER PROCEDURE dbo.TempGetDataForDropDown ( @strColumnNamenvarchar (50) ) as
I am trying to run an sql query with a function in SQL SERVER MANAGEMENT STUDIO and am getting the following error.
Msg 207, Level 16, State 1, Line 9 Invalid column name 'UserID'.
here is my Query ----------------- USE vportal4vsearch GO CREATE FUNCTION dbo.ConcatUserGroups(@UserID int) RETURNS VARCHAR(8000) AS BEGIN DECLARE @groupname Varchar(2000) SELECT @groupname = COALESCE(u.group_name + ', ', '') + CONVERT(varchar(20), u.group_name) FROMdbo.[user] A JOIN dbo.UserGroup_combo UG ON UG.ug_userID = a.USER_ID JOIN dbo.usergroup U ON UG.ug_groupID = u.group_ID WHEREA.USER_ID = @UserID ORDER BY U.GROUP_NAME
RETURN @groupname END GO SELECT user_ID, user_Firstname, user_Lastname, user_Email, Username = (Case When user_Username = ' ' or user_username is Null then 'None' else User_Username end), user_creationdate, Active = (Case When user_Active = 1 then 'Yes' else 'No' end), dbo.ConcatUserGroups(UserID), TheatreCode = (Case When User_TheaterCode = ' ' or User_TheaterCode is Null then 'N/A' else User_TheaterCode end), JobTitle = (Case When user_JobTitle = ' ' or User_Jobtitle is Null then 'N/A' else User_Jobtitle end) FROM [user] GO DROP FUNCTION dbo.ConcatUserGroups GO
Private Sub pulllikehell() Dim cn As SqlCeConnection Dim rda As SqlCeRemoteDataAccess = Nothing Dim sqlEngine As SqlCeEngine
Try
' Create database if it doesn't already exist If (Not File.Exists("My DocumentsORDER.sdf")) Then sqlEngine = New SqlCeEngine sqlEngine.LocalConnectionString = "Data Source=My DocumentsORDER.sdf;"
sqlEngine.CreateDatabase() sqlEngine.Dispose() Else ' Open the connection to the database cn = New SqlCeConnection("Data Source=My Documents" & _ "ORDER.sdf:") cn.Open() Dim cmd As SqlCeCommand = cn.CreateCommand()
' Drop the FieldMemos table cmd.CommandText = "DROP TABLE STAFF" cmd.ExecuteNonQuery()
' Close the connection
End If
' Instantiate the RDA Object rda = New SqlCeRemoteDataAccess ' Connection String to the SQL Server. Dim remoteConnectString As String = "Provider=SQLOLEDB;" & _ "Data Source=KANGALERT/SQLEXPRESS;" & _ "Initial Catalog=ORDER;"
rda.Pull("STAFF", "Select * from STAFF", remoteConnectString, _ RdaTrackOption.TrackingOnWithIndexes) MsgBox("ok")
Catch sqlex As SqlCeException Dim sqlError As SqlCeError For Each sqlError In sqlex.Errors MessageBox.Show(sqlError.Message) Next Catch ex As Exception MessageBox.Show(ex.Message) Finally rda.Dispose() End Try
End Sub
[/CODE]
computer server name is kangalert
and got 2 sqlservice run in my pc, SQLEXPRESS and MSSQLSERVER
1 SELECT 2 RowNumber, 3 'Source.Dbf, Plan.Dbf', 4 'Source Name is missing for Source Number "' + IsNull(RTrim(f.SOURCE_NUM),'Unknown') + '" in Plan.Dbf table.' 5 FROM 6 SourceDbf f 7 JOIN 8 ( 9 SELECT DISTINCT 10 SOURCE_NUM, 11 (Select CASE s.SOURCE_NUMWhen 1 Then SRC1NAME 12 WHEN 2 Then SRC2NAME 13 WHEN 3 THEN SRC3NAME 14 WHEN 4 THEN SRC4NAME 15 WHEN 5 THEN SRC5NAME 16 WHEN 6 THEN SRC6NAME 17 WHEN 7 THEN SRC7NAME 18 WHEN 8 THEN SRC8NAME 19 WHEN 9 THEN SRC9NAME 20 WHEN 10 THEN SRC10NAME 21 WHEN 11 THEN SRC11NAME 22 WHEN 12 THEN SRC12NAME 23 WHEN 13 THEN SRC13NAME 24 WHEN 14 THEN SRC14NAME 25 WHEN 15 THEN SRC15NAME 26 END 27 FROM 28 PlanDBF p 29 Where 30 p.PLAN_NUM = s.PLAN_NUM 31 ) as SourceName 32 FROM 33 SourceDBF s ) c on f.PLAN_NUM = c.PLAN_NUM
i am getting an error on Line 33 and this what the error says... Msg 207, Level 16, State 1, Line 33Invalid column name 'PLAN_NUM'.
I have tried running this query multiple times with no success I get the following errorIncorrect syntax near '('.I tried with quotes and without quotes around the 10 and also without the brackets around variable. It runs when an integer in entered in the variables place but that is not what I want. What am I doing wrong DECLARE @p AS intSET @p='10'SELECT TOP (@p)* FROM my_tbl order by newid()
Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: BC30456: 'InserParameters' is not a member of 'System.Web.UI.WebControls.SqlDataSource'.Source Error:
Line 15: registrationDataSource.InsertCommand = "INSERT TO Reputation (firstname, lastname)VALUES(@First Name, @Last Name)" Line 16: Line 17: registrationDataSource.InserParameters.Add("firstname", firstname.txt) Line 18: registrationDataSource.InserParameters.Add("lastname", lastname.txt) Line 19: Source File: C:UsersQaiphyx eputationDefault.aspx.vb Line: 17 Show Detailed Compiler Output:
strCommand = "SELECT * FROM tblevents WHERE startingDate=#"&startDate &"# AND eventtitle like '%"&criteria &"%' ORDER BY " &sSortSt I want to find any records that match a certain keyword on a specific date... But nothing comes up even though there is an event matching that criteria on the given date. Do I need brackets around my query or something?
EXEC sp_addlinkedserver @server = 'LinkedServer', --Server Name @provider = 'Microsoft.Jet.OLEDB.4.0', --Provider Name @srvproduct = 'OLE DB Provider for Jet', --Product @datasrc = 'C:DataX2000Master.mdb' --Data Source
Before the above query was okay..... I used to run the same query as I today ran but I got this error message, any help pls.....
Server: Msg 7370, Level 16, State 2, Line 1 One or more properties could not be set on the query for OLE DB provider 'Microsoft.Jet.OLEDB.4.0'. The provider could not support a required property.
From Traveler_X3 trv Join Recipe_X3 rcp On (trv.RecipeID = rcp.RecipeID)
Where trv.Oper = rtsA.oper And trv.RouteGroupID = ( Select rgp.routeGroupID
From Route_Group_X3 rgp
Where rgp.routeGroupName = ( Select rtl.RouteGroup
From RouteList_X3 rtl
WHERE rtl.route = rtsA.route ) ) ))
FROM Routes_X3 rtsA
where rtsA.route=( SELECT lhm.route
FROM brettb.pdash2.dbo.lothistorymoves lhm, x3oprs x3o
WHERE lhm.lot = 'S6D0IQ002A' AND lhm.oper = x3o.oper AND lhm.date_time = (SELECT max(date_time) FROM brettb.pdash2.dbo.lothistorymoves lhm, x3oprs x3o WHERE lhm.lot = 'S6D0IQ002A' AND lhm.oper = x3o.oper) )
and rtsA.seq BETWEEN ( SELECT seq
FROM Routes_X3
WHERE oper =( SELECT lhm.oper
FROM brettb.pdash2.dbo.lothistorymoves lhm
WHERE lhm.lot ='S6D0IQ002A' AND lhm.date_time = (SELECT max(date_time) FROM brettb.pdash2.dbo.lothistorymoves lhm WHERE lhm.lot = 'S6D0IQ002A') )
and route=( select top 1 lhm.route
FROM brettb.pdash2.dbo.lothistorymoves lhm, x3oprs x3o
WHERE lhm.lot = 'S6D0IQ002A' AND lhm.oper = x3o.oper AND lhm.date_time = (SELECT max(date_time) FROM brettb.pdash2.dbo.lothistorymoves lhm, x3oprs x3o WHERE lhm.lot ='S6D0IQ002A' AND lhm.oper = x3o.oper) ) )+1 and 219;
What i got working was to put the query in a temp table called #temp1 and then run this: select sum(theoreticalTime) from #temp1;
Hi, I recently modified all the messages with severity 15 and 16 to be logged in windows applications log... I then discovered that my Application is generating lots of errors of type:
Error: 16945, Severity: 16, State: 1 The cursor was not declared.
followed by
Error: 16955, Severity: 16, State: 2 Could not create an acceptable cursor.
I think this error is occuring since a lot, but I discovered it now because I recently modified which messages are logged (I added those with severity of 15 and 16).
This error is occuring everytime (one error every 3 minutes!!)... I dont know what part of my app is having trouble, i think its a bug of sql server... Does somebody know anything about this error?
SET @EventName = 'DIVIDEND' SET @Ticker = 'IBM' SET @Cusip = ''
SET @Filter = 'Name like ''' + @EventName + '%'' AND Ticker Like ''' + @Ticker + '%'' AND Cusip like ''' + @Cusip + '%'''
Select * from eventdatadetails where @Filter
I want to execute the above SELECT statement and the filters in the where clause should come from the @Fitler variable... but query analyzer gives an error. If i replace the data in the @Filter with the variable in the query, everything works fine ...
I'm very new to SQL. YOur help is appreciated. Ok system_user is the main table. All the CREATED_BY and LAST_UPDATED_BY columns in all tables are supposed to reference back to the system_user table. Anything with _TYPE (i.e. CONTACT_TYPE, ADDRESS_TYPE ) is supposed to map to common_lookup table.
Heres the error I get: ERROR at line 12: no mathiching unique or primary key for this column-list.
Heres where I I think I have the mistakes. Pks and FKs
Thank you.
CREATE TABLE system_user ( SYSTEM_USER_ID NUMBER , SYSTEM_USER_NAME VARCHAR2(20) , SYSTEM_USER_GROUP_ID NUMBER , SYSTEM_USER_TYPE NUMBER , LAST_NAME VARCHAR2(20) , FIRST_NAME VARCHAR2(20) , MIDDLE_INITIAL VARCHAR2(1) , CREATED_BY NUMBER CONSTRAINT nn_system_user_1 NOT NULL , CREATION_DATE DATE , LAST_UPDATED_BY NUMBER CONSTRAINT nn_system_user_2 NOT NULL , LAST_UPDATE_DATE DATE , CONSTRAINT pk_system_user_1 PRIMARY KEY (SYSTEM_USER_ID, CREATED_BY, LAST_UPDATED_BY));
CREATE TABLE common_lookup ( COMMON_LOOKUP_ID NUMBER , COMMON_LOOKUP_CONTEXT VARCHAR2(30) , COMMON_LOOKUP_TYPE VARCHAR2(30) , COMMON_LOOKUP_MEANING VARCHAR2(30) , CREATED_BY NUMBER CONSTRAINT common_lookup_1 NOT NULL , CREATION_DATE DATE , LAST_UPDATED_BY NUMBER CONSTRAINT common_lookup_2 NOT NULL , LAST_UPDATE_DATE DATE , CONSTRAINT pk_common_lookup_1 PRIMARY KEY (COMMON_LOOKUP_ID) , CONSTRAINT fk_common_lookup_1 FOREIGN KEY (CREATED_BY) REFERENCES system_user (CREATED_BY) , CONSTRAINT fk_common_lookup_2 FOREIGN KEY (LAST_UPDATED_BY) REFERENCES system_user (LAST_UPDATED_BY));
CREATE TABLE contact ( CONTACT_ID NUMBER , MEMBER_ID NUMBER , CONTACT_TYPE NUMBER CONSTRAINT nn_contact_1 NOT NULL , LAST_NAME VARCHAR2(20) , FIRST_NAME VARCHAR2(20) , MIDDLE_INITIAL VARCHAR2(1) , CREATED_BY NUMBER CONSTRAINT nn_contact_2 NOT NULL , CREATION_DATE DATE , LAST_UPDATED_BY NUMBER CONSTRAINT nn_contact_3 NOT NULL , LAST_UPDATE_DATE DATE , CONSTRAINT pk_contact_1 PRIMARY KEY (CONTACT_ID) , CONSTRAINT fk_contact_1 FOREIGN KEY (CONTACT_TYPE) REFERENCES common_lookup (COMMON_LOOKUP_ID) , CONSTRAINT fk_contact_2 FOREIGN KEY (CREATED_BY) REFERENCES system_user (CREATED_BY) , CONSTRAINT fk_contact_3 FOREIGN KEY (LAST_UPDATED_BY) REFERENCES system_user (LAST_UPDATED_BY));
CREATE TABLE address ( ADDRESS_ID NUMBER , CONTACT_ID NUMBER CONSTRAINT nn_address_1 NOT NULL , ADDRESS_TYPE NUMBER CONSTRAINT nn_address_2 NOT NULL , CITY VARCHAR2(30) , STATE_PROVINCE VARCHAR2(30) , POSTAL_CODE VARCHAR2(20) , CREATED_BY NUMBER CONSTRAINT nn_address_3 NOT NULL , CREATION_DATE DATE , LAST_UPDATED_BY NUMBER CONSTRAINT nn_address_4 NOT NULL , LAST_UPDATE_DATE DATE , CONSTRAINT pk_address_1 PRIMARY KEY (ADDRESS_ID) , CONSTRAINT fk_address_1 FOREIGN KEY (CONTACT_ID) REFERENCES contact (CONTACT_ID) , CONSTRAINT fk_address_2 FOREIGN KEY (ADDRESS_TYPE) REFERENCES system_user (COMMON_LOOKUP_ID) , CONSTRAINT fk_address_3 FOREIGN KEY (CREATED_BY) REFERENCES system_user (CREATED_BY); , CONSTRAINT fk_address_4 FOREIGN KEY (LAST_UPDATED_BY) REFERENCES system_user (LAST_UPDATED_BY));
CREATE TABLE telephone ( TELEPHONE_ID NUMBER , CONTACT_ID NUMBER CONSTRAINT nn_telephone_1 NOT NULL , ADDRESS_ID NUMBER CONSTRAINT nn_telephone_2 NOT NULL , TELEPHONE_TYPE NUMBER CONSTRAINT nn_telephone_3 NOT NULL , COUNTRY_CODE VARCHAR2(3) , AREA_CODE VARCHAR2(6) , TELEPHONE_NUMBER VARCHAR2(10) , CREATED_BY NUMBER CONSTRAINT nn_telephone_4 NOT NULL , CREATION_DATE DATE , LAST_UPDATED_BY NUMBER CONSTRAINT nn_telephone_5 NOT NULL , LAST_UPDATE_DATE DATE , CONSTRAINT pk_telephone_1 PRIMARY KEY (TELEPHONE_ID) , CONSTRAINT fk_telephone_1 FOREIGN KEY (CONTACT_ID) REFERENCES contact (CONTACT_ID) , CONSTRAINT fk_telephone_2 FOREIGN KEY (ADDRESS_ID) REFERENCES address (ADDRESS_ID) , CONSTRAINT fk_telephone_3 FOREIGN KEY (TELEPHONE_TYPE) REFERENCES system_user (COMMON_LOOKUP_ID) , CONSTRAINT fk_telephone_4 FOREIGN KEY (CREATED_BY) REFERENCES system_user (CREATED_BY); , CONSTRAINT fk_telephone_5 FOREIGN KEY (LAST_UPDATED_BY) REFERENCES system_user (LAST_UPDATED_BY));
I am running this piece of code to execute a package programatically and Yet I get Failure. What could be Wrong with this. If so can anyone tell me How I can debug in SSIS.
Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. original source code
Hi,I have code on a page to update one table and insert info into another, but I cant make it work. I am new to coding and i think there are many mistakes. Please can someone pick out a few that need to be changed for the page to work.Code:private bool ExecuteUpdate(int quantity){ SqlConnection con = new SqlConnection(); con.ConnectionString = "ConnectionString"; con.Open(); SqlCommand command = new SqlCommand(); command.Connection = con; TextBox TextBox1 = (TextBox)FormView1.FindControl("TextBox1"); Label labname = (Label)FormView1.FindControl("Label3"); Label labid = (Label)FormView1.FindControl("Label13"); command.CommandText = "UPDATE Items SET Quantityavailable WHERE productID='@productID' = " + TextBox1.Text + command.ExecuteNonQuery(); return true; con.Close();} private bool ExecuteInsert(String quantity) { SqlConnection con = new SqlConnection(); con.ConnectionString = "ConnectionString"; con.Open(); SqlCommand command = new SqlCommand(); command.Connection = con; TextBox TextBox1 = (TextBox)FormView1.FindControl("TextBox1"); Label labname = (Label)FormView1.FindControl("Label3"); Label labid = (Label)FormView1.FindControl("Label13"); command.CommandText = "INSERT Transactions SET Usersname = @UserName" + "; INSERT Transactions SET Itemid WHERE productID='@productID' = @productID; INSERT Transactions SET itemname = @Itemsname" + "; INSERT Transactions SET Date WHERE productID='@productID' = " + DateTime.Now.ToString() + "; INSERT Transactions SET Qty WHERE productID='@productID' = " + TextBox1.Text; command.Parameters.Add("@UserName", System.Web.HttpContext.Current.User.Identity.Name); command.Parameters.Add("@Itemsname", labname.Text); command.Parameters.Add("@productID", labid.Text); command.ExecuteNonQuery(); return true; con.Close(); }protected void Button2_Click(object sender, EventArgs e){ TextBox TextBox1 = FormView1.FindControl("TextBox1") as TextBox; ExecuteUpdate(Int32.Parse(TextBox1.Text) ); ExecuteInsert(Int32.Parse);} Current error message is:The best overloaded method match for 'detailproview.ExecuteInsert(string)' has some invalid argumentsto Line 74: ExecuteInsert(Int32.Parse); Thanks if someone can help!Jon
Hello All, i am trying to connect to SQL Database using OleDb connection, but i keep getting error. here is my connection code. string strCon = "Provider=SQLOLEDB.1;Data source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"; OleDbConnection con = null; OleDbCommand cmd = null; con = new OleDbConnection(strCon); con.Open(); // deleting the exisitng one// cmd = con.CreateCommand(); cmd.CommandText = "DELETE FROM Detail"; cmd.ExecuteNonQuery(); con.Close(); con.Dispose(); con = null;this is the error i am getting ..........No error message available, result code: DB_E_ERRORSOCCURRED(0x80040E21). 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.Data.OleDb.OleDbException: No error message available, result code: DB_E_ERRORSOCCURRED(0x80040E21).Source Error:
Line 43: OleDbCommand cmd = null;Line 44: con = new OleDbConnection(strCon);Line 45: con.Open();Line 46: // deleting the exisitng one//Line 47: cmd = con.CreateCommand(); can some please tell me where i am making the mistake. I really appreciate it.Thanks
UPDATE CART SET TOTAL_COUNT = TOTAL_COUNT + 1, SET TOTAL_COUNT1 = TOTAL_COUNT1 + 1, SET DATE1 = 10/30/2006 6:17:02 PM, SET PERSON = luke WHERE CART_ID = 1
I have wacked my head over this query I dont see anything wrong with it
Ive got the following SQL query and i want to return only distinct [ReviewID]'s, however SQL Server is complaining about it. This is the query:
SELECT DISTINCT Top 5 [ReviewID],[ReviewType],[ReviewTypeName],[LoginID],[LoginForename],[LoginSurname],[Approved],[ReviewDate] ,[Stars],[RelatedProductID],[Title],[Copy],[Rating], [Image1], [Image1Width], [Image1Height], [Image1AltText], [Image2], [Image2Width], [Image2Height], [Image2AltText], [CategoryL4] FROM [feManagedReview]
This is whats its complaining about:
Msg 421, Level 16, State 1, Line 1 The text data type cannot be selected as DISTINCT because it is not comparable. Msg 421, Level 16, State 1, Line 1 The text data type cannot be selected as DISTINCT because it is not comparable. Msg 421, Level 16, State 1, Line 1 The text data type cannot be selected as DISTINCT because it is not comparable.
I wrote this update statement and it looks right but I keep getting an error that says "incorrect syntax next to c" what did I do wrong?
Here is the statement:
UPDATE tblclients c SET intproviderId = (SELECT TOP 1 t.inttransferid FROM tbltransfer t WHERE t.intclientids = c.intclientid ORDER BY t.inttransferid DESC)
The following sql statement is rejected by asp.net (working with sqlserver). It says something is wrong near "TableFlights". But I don'tsee anything wrong with it.Any help is appreciated:SELECT TableFlights.IdFlight, Concat = (TableFlights.OrganizerLastName+ ', ' + TableFlights.OrganizerFirstName + ' Flt:' +TableFlights.FlightNumber + ' on ' +Convert(char(10,TableFlights.FlightDate,101)) FROM TableFlights INNERJOIN TablePassengers ON TableFlights.IdFlight=TablePassengers.IdFlightWhere TablePassengers.Email = 'marvin@micro-net.com' Order ByTableFlights.OrganizerLastName, TableFlights.OrganizerFirstName-- Marvin
Im getting way too many rows retured..what its trying to do is inserta 0 for revenue for months 7 - 12 (aka July through December) for eachof these cost centers for each payor type..Im getting a lot of repeatsand the concatenation field date always comes back as January 2003instead of the month and date its supposed to--Fiscal Yeardeclare @year smallintset @year = 2004--Month number the Fiscal year starts and endsdeclare @month smallintset @month = 7--Place holder for number of costcentersdeclare @cccounter smallint--loop counter for cost centersdeclare @ccount smallintset @ccount = 1--Place holder for number of payor typesdeclare @ptcounter smallint--loop counter for payor typesdeclare @pcount smallintset @pcount = 1--Temp table to store the blank values for all cost centers/payortypes for the fiscal yeardeclare @Recorded_Revenue_tmp table(Revenue money default 0,[Date] varchar(15),monthn smallint,yearn smallint,[CostCenter] varchar(50),[PayorType] varchar(50))--Temp table to store the values of the cost centersdeclare @costcenter_tmp table(ccid int IDENTITY (1,1),ccname varchar(50))--Inserts cost centers and code into the @costcenter_tmp temp tableinsert into @costcenter_tmp (ccname) select costcenter.fullname + ' '+ costcenter.code from costcenter, agency_cost_centerwhere costcenter.oid = agency_cost_center.cost_center_moniker--Sets the @cccounter variable to the number of cost centersselect @cccounter = count(*) from @costcenter_tmp--Temp table to store the values of the payor typesdeclare @payor_type_tmp table(ptid int identity (1,1),ptname varchar(50))--Inserts payor types into the @payor_type_tmp temp tableInsert into @payor_type_tmp(ptname)select fullname from payor_type,payorwhere payor_type.oid = payor.payor_type_moniker--Sets the @ptcounter variable to the number of payor typesselect @ptcounter = count(*) from @payor_type_tmp--Loop that gets the first part of the fiscal yearWhile (@month <13)begin--Loop that gets the value of the cost center to insertWhile (@ccount <= @cccounter)begin--Loop that inserts values for the first part of the fiscal year intothe @Recorded_Revenue_tmp temp tablewhile (@pcount <= @ptcounter)beginInsert into @Recorded_Revenue_tmp(Revenue, [Date], monthn,yearn,[CostCenter],[PayorType])select 0, datename(month, @month)+ ' ' + cast(@year -1 as varchar(4)),@month, @year -1, ccname, ptnamefrom @costcenter_tmp ct,@payor_type_tmp pt where ct.ccid = @ccount andpt.ptid = @pcountset @pcount = @pcount + 1endset @pcount = 1set @ccount = @ccount + 1endset @ccount = 1set @month = @month + 1endselect * from @Recorded_Revenue_tmpsample return data:(returns 16008 rows!!!)..0000January 200372003Genesis Assertive Community Treatment Team250SAGA..0000January 200372003Genesis Assertive Community Treatment Team250Self Pay..0000January 200372003Genesis Assertive Community Treatment Team250ABH..0000January 200372003Genesis Assertive Community Treatment Team250Managed Medicaid..0000January 200372003Genesis Assertive Community Treatment Team250Managed Medicaid..0000January 200372003Genesis Assertive Community Treatment Team250Managed Medicaid..0000January 200372003Genesis Assertive Community Treatment Team250Managed Medicaid..0000January 200372003Genesis Assertive Community Treatment Team250Commercial..0000January 200372003Genesis Assertive Community Treatment Team250Commercial..0000January 200372003Genesis Assertive Community Treatment Team250Commercial..0000January 200372003Genesis Assertive Community Treatment Team250Commercialthanks -Jim