I am trying to set a column name to a declared variable but i keep getting invalid column name message. what is the right syntax? Here is the query
Declare #APPSHELTER Table
(tid int Identity(1,1),App_Id Numeric,PrimaryName Varchar(300),--EmployerAdress Varchar(500), rent_amt varchar(20),house_payment_amt varchar(20),ins_amt varchar(20),utilities_amt varchar(20),Trash_Collection_amt varchar(20),Sewerage_amt varchar(20),Telephone_amt varchar(20),water_amt varchar(20),other_amt varchar(20), total varchar(20), property_taxes_amt varchar(20),insurance_amt varchar(20), other_house_amt varchar(20), gas_amt varchar(20), elec_amt varchar(20), otherfuel_amt varchar(20))
DECLARE #rent_amt_h NUMERIC
DECLARE #house_payment_amt_h NUMERIC
DECLARE #insurance_amt_h NUMERIC
DECLARE #property_taxes_amt_h NUMERIC
DECLARE #Other_house_amt_h NUMERIC
DECLARE #gas_amt_u NUMERIC
DECLARE #elec_amt_u NUMERIC
DECLARE #otherfuel_amt_u NUMERIC
DECLARE #Trash_Collection_amt_u NUMERIC
DECLARE #Sewerage_amt_u NUMERIC
DECLARE #Telephone_amt_u NUMERIC
DECLARE #water_amt_u NUMERIC
DECLARE #other_amt_u NUMERIC
DECLARE #total_u NUMERIC
insert into #APPSHELTER(App_Id,PrimaryName,rent_amt,house_payment_amt,ins_amt,utilities_amt,Trash_Collection_amt,Sewerage_amt,Telephone_amt,water_amt,other_amt,total, property_taxes_amt, insurance_amt, other_house_amt, gas_amt, elec_amt, otherfuel_amt )
select #app_id,
ISNULL((select top 1 replace(first_name,'''','''''') + ' ' + isnull(replace(middle_name,'''',''''''),'') + ' '+replace(last_name,'''','''''')
from app_member (nolock)
where app_id = #app_id and msn=1),'') AS PrimaryName,
isnull(rent_amt,'0' ) AS rent_amt,
isnull(house_payment_amt,'0') AS house_payment_amt,
isnull((insurance_amt+property_taxes_amt),'0') AS ins_amt,
--isnull(HC_Costs_amt,'0') AS utilities_amt,
isnull(gas_amt,'0') + isnull(elec_amt,'0') + isnull(otherfuel_amt,'0') as utilities_amt,
isnull(Trash_Collection_amt,'0') AS Trash_Collection_amt,
isnull(Sewerage_amt,'0') AS Sewerage_amt,
isnull(Telephone_amt,'0') AS Telephone_amt,
isnull(water_amt,'0') AS water_amt,
isnull(other_amt,'0') + isnull(other_house_amt,'0') AS other_amt,
isnull(total,'0') AS total,
isnull(property_taxes_amt,'0' ) AS property_taxes_amt,
isnull(insurance_amt,'0' ) AS insurance_amt,
isnull(other_house_amt,'0' ) AS other_house_amt,
isnull(gas_amt,'0' ) AS gas_amt,
isnull(elec_amt,'0' ) AS elec_amt,
isnull(otherfuel_amt,'0' ) AS otherfuel_amt
from Ext_App_Group_Other_Expenses APP_DEP (nolock)
WHERE APP_DEP.APP_ID=#APP_ID
SET #rent_amt_h = 'rent_amt'
SET #house_payment_amt_h = 'house_payment_amt'
SET #insurance_amt_h = 'insurance_amt'
SET #property_taxes_amt_h = 'property_taxes_amt'
SET #Other_house_amt_h = 'other_house_amt'
SET #gas_amt_u = 'gas_amt'
SET #elec_amt_u = 'elec_amt'
SET #otherfuel_amt_u = 'otherfuel_amt'
SET #Trash_Collection_amt_u = 'Trash_Collection_amt'
SET #Sewerage_amt_u = 'Sewerage_amt'
SET #Telephone_amt_u = 'Telephone_amt'
SET #water_amt_u = 'water_amt'
SET #other_amt_u = 'other_amt'
SET #total_u = 'total'
DECLARE #APPSHELTER_COUNT INT
if (rent_amt!=0 or house_payment_amt!=0 or insurance_amt != 0 or property_taxes_amt != 0 or gas_amt != 0 or elec_amt != 0 or otherfuel_amt != 0 or Trash_Collection_amt != 0 or Sewerage_amt != 0 or Telephone_amt != 0 or water_amt != 0 or other_house_amt != 0 or other_amt != 0 or total !=0)
begin
SET #APPSHELTER_COUNT = (select Count(APP_ID) FROM ext_app_group_other_expenses (nolock) WHERE APP_ID = #App_Id )
end
else
begin
SET #APPSHELTER_COUNT = 0
end
Actually, I am trying the check whether the values in these text boxes are null or not. If not I have to set the count!
2 things:
(1). I think this is erroneous - I don't see these variables declared anywhere....
if (rent_amt!=0 or house_payment_amt!=0 or insurance_amt != 0 or property_taxes_amt != 0 or gas_amt != 0 or elec_amt != 0 or otherfuel_amt != 0 or Trash_Collection_amt != 0 or Sewerage_amt != 0 or Telephone_amt != 0 or water_amt != 0 or other_house_amt != 0 or other_amt != 0 or total !=0)
(2). You defined a bunch of variables at the top #rent_amt_h, #house_payment_amt_h, etc as NUMERIC, but then at the bottom you are setting them to a string value. This will also throw an error - if you are trying to say that these are your column names, then this is not the way to do it - you aren't selecting it anywhere, either. Please clarify what you are hoping to achieve...
Please find below simplified code which seemed to meet your requirements. To test it change values from 0 to 1 in insert statement:
-- Dynamic SQL command string variable
DECLARE #cmdSQL VARCHAR(1000)
-- Column names
DECLARE #rent_amt_h VARCHAR(20) = 'App_Id'
DECLARE #house_payment_amt_h VARCHAR(20) = 'PrimaryName'
-- Count variable
DECLARE #APPSHELTER_COUNT INT
-- Make SQL command
SET #cmdSQL = '
Declare #APPSHELTER Table
(App_Id Numeric,PrimaryName Varchar(300))
insert into #APPSHELTER(App_Id,PrimaryName) values (0,0)
SELECT * FROM #APPSHELTER WHERE ' + #rent_amt_h + ' !=0 OR ' + #house_payment_amt_h + ' != 0'
-- Execute dynamic SQL
EXEC(#cmdsql)
IF ##ROWCOUNT != 0
SET #APPSHELTER_COUNT = 1
ELSE
SET #APPSHELTER_COUNT = 0
SELECT #APPSHELTER_COUNT
Related
I need to create a consecutive sequence of varchar(5) (always 5 chars only) code starting from PREVIOUS code.
For example
'00000', '00001', '00002'...'00009', '0000A', '0000B'...'0000Z', '00010','00011'...'ZZZZZ'.
So if I have #PREVIOUS_CODE = '00000', #NEXT_CODE will be '00001'.
If I have #PREVIOUS_CODE = '00009', #NEXT_CODE will be '0000A'
If I have #PREVIOUS_CODE = '0000Z', #NEXT_CODE will be '00010'
So I need something like that
USE [DATABASE]
GO
CREATE PROCEDURE [dbo].[spGetNextCode]
#PREVIOUS_CODE VARCHAR(5)
AS
DECLARE #NEXT_CODE VARCHAR(5)
DO STUFF
...
SELECT #NEXT_CODE AS NEXT_CODE
GO
Any Help?
Just keep an integer counter in the same table and convert it. I'm using the following SQL Server function in one of my applications:
CREATE FUNCTION [dbo].[GetAlphanumericCode]
(
#number BIGINT,
#leadingzeroes INT = 0
)
RETURNS varchar(255)
AS
BEGIN
DECLARE #charPool varchar(36)
SET #charPool = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
DECLARE #result varchar(255)
IF #number < 0
RETURN ''
IF #number = 0
SET #result = '0'
ELSE BEGIN
SET #result = ''
WHILE (#number > 0)
BEGIN
SET #result = substring(#charPool, #number % 36 + 1, 1) + #result
SET #number = #number / 36
END
END
IF #leadingzeroes > 0 AND len(#result) < #leadingzeroes
SET #result = right(replicate('0', #leadingzeroes) + #result, #leadingzeroes)
RETURN #result
END
It should be a trivial task to rewrite it as a stored procedure
Below is the code snippet in which MIN function using. When execute below code it is giving an error.
CREATE FUNCTION [dbo].[FN_TempCalcTransportExemp]
(
#EmployeeID varchar(20),
#PayElement varchar(20),
#Month varchar(10),
#FinYear varchar(10)
)
RETURNS decimal
AS
BEGIN
DECLARE #TarnsportExemption decimal(18,2) = 0
DECLARE #TDSIsFullExemption bit
DECLARE #PermanentPhysicalDisability decimal(18,2) = 0
DECLARE #UsingComapnyCar bit
DECLARE #Conveyance decimal(18,2) = 0
DECLARE #TransYes decimal(18,2) = 0
DECLARE #TransNo decimal(18,2) = 0
DECLARE #MinConveyance decimal(18,2) = 0
DECLARE #MinTransport decimal(18,2) = 0
SELECT
#TDSIsFullExemption = TDSDetailsFullExemption,
#TransYes = TDSDetailsYes,
#TransNo = TDSDetailsNo
FROM
tbl_TDSSettingDetails
WHERE
TDSSettingsDetailID = 2
SELECT
#Conveyance = #Month
FROM
tbl_Income
WHERE
EmployeeID = #EmployeeID
AND Element = #PayElement
AND FinancialYear = #FinYear
SELECT
#UsingComapnyCar = UsingCompanyCar,
#PermanentPhysicalDisability = PermanentPhysicalDisability
FROM
tbl_Employee_TDS
WHERE
EmployeeID = #EmployeeID
AND TDSFinancialYear = #FinYear
IF (#TDSIsFullExemption = 1)
BEGIN
SET #TarnsportExemption = #Conveyance
END
ELSE
BEGIN
IF (#UsingComapnyCar = 1)
BEGIN
IF (#Conveyance = 0)
BEGIN
SET #MinConveyance = 0
END
ELSE
BEGIN
SET #MinConveyance = #Conveyance
END
IF (#PermanentPhysicalDisability = 1)
BEGIN
SET #MinTransport = #TransYes
END
ELSE
BEGIN
SET #MinTransport = #TransNo
END
SET #TarnsportExemption = MIN(#MinConveyance, #MinTransport)
END
ELSE
BEGIN
SET #TarnsportExemption = 0
END
END
RETURN #TarnsportExemption
END
Error Message:
Msg 174, Level 15, State 1, Procedure FN_TempCalcTransportExemp, Line
66
The MIN function requires 1 argument(s).
set #TarnsportExemption = MIN(#MinConveyance,#MinTransport) - The MIN function is not what you think it is.
You probably want to do something like this:
set #TarnsportExemption = CASE WHEN #MinConveyance < #MinTransport THEN
#MinConveyance
ELSE
#MinTransport
END
Another option is this:
SELECT #TarnsportExemption = MIN(val)
FROM
(
SELECT #MinConveyance as val
UNION ALL
SELECT #MinTransport as val
)
And one more option is to use the values clause:
SELECT #TarnsportExemption = MIN(val)
FROM (VALUES ( #MinConveyance), (#MinTransport)) AS value(val)
Change your min statement like below MIN. Please refer MIN (Transact-SQL)
--fROM
set #TarnsportExemption = MIN(#MinConveyance,#MinTransport)
--To
SELECT #TarnsportExemption = MIN(A) FROM (
SELECT #MinConveyance A
UNION ALL
SELECT #MinTransport
)AS AA
In SQL, MIN function will return you minimum value of a column from selected list; so you can use MIN only in inline queries.
e.g. Select min(Salary) from Tbl_Employee
So, in your case either you can use case when then or union all to get minimum value from two variables as:-
SET #TarnsportExemption = CASE WHEN #MinConveyance < #MinTransport THEN #MinConveyance ELSE #MinTransport END
OR
SELECT #TarnsportExemption = MIN(TEMPS.[VALUE])
FROM (
SELECT #MinConveyance AS VALUE
UNION ALL
SELECT #MinTransport AS VALUE
) AS TEMPS
I have the following SP
CREATE PROCEDURE [dbo].[GetBaseSixtyTwoString]
#a_number_to_convert int,
#v_temp_val nvarchar(256) output
AS
DECLARE #v_modulo INTEGER;
DECLARE #v_temp_int decimal(38) = #a_number_to_convert;
DECLARE #v_temp_char VARCHAR(1);
DECLARE #c_base62_digits VARCHAR(62) = '0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ';
IF ( #a_number_to_convert = 0 )
BEGIN
SET #v_temp_val = '5';
END
WHILE ( #v_temp_int <> 0 )
BEGIN
SET #v_modulo = #v_temp_int % 62;
SET #v_temp_char = substring( #c_base62_digits, #v_modulo + 1, 1 );
SET #v_temp_val = #v_temp_char + #v_temp_val;
SET #v_temp_int = floor(#v_temp_int / 62);
END
I am calling it like this:
declare #shorturl nvarchar(256)
exec dbo.GetBaseSixtyTwoString 1, #shorturl output
But the variable #shorturl always returns null
However if I put print statements in the SP I can see that #v_temp_val is indeed getting the correct value.
What am I missing?
You need to initialise #v_temp_val inside the stored procedure to non-NULL value, to ''.
If #v_temp_val is NULL, then this line would still result in NULL:
SET #v_temp_val = #v_temp_char + #v_temp_val;
because "value" + NULL = NULL
check if any value you put into variable #v_temp_val is null. note that any non-null value + NULL will result to NULL:
SET #v_temp_val = ISNULL(#v_temp_char, '') + ISNULL(#v_temp_val, '');
I have created a Function in SQL Server 2012 that I will use in a Check Constraint on a table.
The function works as expected if I do:
SELECT [dbo].[CheckValidCardnumberForShellTankingen] ('700678036658047691' ,'2925CA00-6DD5-4F9D-AB0E-AA15DBBD388B')
But when I try to set the expression in Check Constraint so:
([dbo].[CheckValidCardnumberForShellTankingen]([Volledig kaartnummer],[RollBackCode])=(1))
I get a Messaage: "Error validating constraint 'CK_MyConstraint'"
I use the Uniqueidentifier in a Where clause and the strange thing is if I replace the parameter with string containing the Uniqueidentifier I dont get this error.
Here is the Function:
-- =============================================
-- Author: Anders Pedersen
-- Create date: 2015-02-13
-- Description: Check of the Cardnumber of a transaction is valid.
-- =============================================
CREATE FUNCTION [dbo].[CheckValidCardnumberForShellTankingen]
(
-- Add the parameters for the function here
#Cardnumber NvarChar(50),
#RollBackCode NvarChar(200)
)
RETURNS BIT
AS
BEGIN
-- Declare the return variable here
DECLARE
#Result BIT
,#ResultLenght BIT
,#ResultPrefix BIT
,#CardLenght INT
,#SupplierID INT
,#UseCardnumber BIT
,#Prefix NvarChar(50)
-- Add the T-SQL statements to compute the return value here
SET #Result = 0
SET #ResultLenght = 0
SET #ResultPrefix = 0
SET #CardLenght = -1
SET #SupplierID = -1
SET #UseCardnumber = 0
SET #Prefix = ''
-- Get the UseCardnumber and the SupplierID
SELECT #UseCardnumber = C.UseCardNumber, #SupplierID = F.SupplierID
FROM Client C INNER JOIN
ClientFileUploads F ON C.ClientID = F.ClientID
WHERE F.RollBackCode = #RollBackCode
--WHERE F.RollBackCode = '2925CA00-6DD5-4F9D-AB0E-AA15DBBD388B'
-- Only carry out the check if the Client use Cards else set the check to True (1)
IF #UseCardnumber = 1
BEGIN
SELECT #CardLenght = [CardNumberLenght], #Prefix = ISNULL([Prefix],'') FROM [dbo].[Supplier] AS S WHERE S.SupplierID = #SupplierID
IF (#CardLenght IS NULL) OR (#CardLenght = 0)
BEGIN
SET #ResultLenght = 1
END
ELSE
BEGIN
IF (LEN(#Cardnumber) - #CardLenght)= 0
BEGIN
SET #ResultLenght = 1
END
ELSE
BEGIN
SET #ResultLenght = 0
END
END
IF SUBSTRING(#Cardnumber, 1, LEN(#Prefix)) = #Prefix
BEGIN
SET #ResultPrefix = 1
END
ELSE
BEGIN
SET #ResultPrefix = 0
END
IF ((#ResultLenght = 1) AND (#ResultPrefix = 1))
BEGIN
SET #Result = 1
END
ELSE
BEGIN
SET #Result = 0
END
END
ELSE
BEGIN
SET #Result = 1
END
-- Return the result of the function
RETURN #Result
END
GO
If #RollBackCode is a uniqueidentifier, I recommend making the parameter a uniqueidentifier and not a varchar.
As Rhys Jones points out, you shouldn't use a UDF in a check constraint.
See
https://dba.stackexchange.com/questions/22297/udf-in-check-constraint-downside
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/078b720f-faac-425c-b51a-33bcecb263d2/check-constraint-with-udf-problem-with-lots-of-data?forum=transactsql
http://sqlblog.com/blogs/tibor_karaszi/archive/2009/12/17/be-careful-with-constraints-calling-udfs.aspx
If you need to check in a trigger and roll back -- SQL Server - After Insert/ For Insert - Rollback
I am getting the following error
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name.
for the query show below:
CREATE PROC [dbo].[Sp_Table1] #ctlg_ipt_event_id int
AS
SET NOCOUNT ON
DECLARE #current_status NCHAR(1), #ready_status_code NCHAR(1)
DECLARE #current_action NCHAR(1), #ready_action_code NCHAR(1), #done_action_code NCHAR(1)
DECLARE #pst_user_id int
SELECT #current_status = status_code
,#current_action = action_code
,#pst_user_id = last_mod_user_id
FROM merch_ctlg_ipt_event
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
Select #ready_status_code = 'o'
, #ready_action_code = 'a'
, #done_action_code = 'b'
IF #current_status <> #ready_status_code OR #current_action <> #ready_action_code
BEGIN
RETURN
END
BEGIN TRAN
declare #rows int
,#err int
,#i int
,#name nvarchar(50) --COLLATE SQL_AltDiction_Pref_CP850_CI_AS
,#resolved_View_Name_category_id int
,#xref_value int
,#availability_start_date datetime
,#availability_end_date datetime
,#status_code int
,#last_mod_user_id int
,#CT datetime
,#supplier_id int
,#View_Name_id int
select #i = 1
,#CT = current_timestamp
Select Distinct mc.name,
mc.resolved_View_Name_category_id,
mc.xref_value,
mc.availability_start_date,
mc.availability_end_date,
mc.status_code,
CASE WHEN mc.last_mod_user_id = 42
THEN #pst_user_id
ELSE mc.last_mod_user_id
END as last_mod_user_id,
CURRENT_tsp
,IDENTITY(int,1,1) as rn
,si.supplier_id
,si.View_Name_id
into #temp
FROM View_Name AS si
JOIN merch_ctlg_ipt_View_Name AS mc
ON mc.supplier_id = si.supplier_id
AND mc.resolved_View_Name_id = si.View_Name_id
AND mc.cat_imp_event_id = #ctlg_ipt_event_id
AND mc.accept_flag = 'y'
WHERE si.shipper_flag = 'n'
select #rows=##ROWCOUNT,#err=##error
if #rows > 0 and #err=0
Begin
While #i <=#rows
begin
SElect #name = name,
#resolved_View_Name_category_id = resolved_View_Name_category_id,
#xref_value = xref_value,
#availability_start_date = availability_start_date,
#availability_end_date = availability_end_date,
#status_code = mc.status_code,
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
,#supplier_id=supplier_id
,#View_Name_id=View_Name_id
from #temp
Where rn=#i
UPDATE View_Name
SET name = #name,
View_Name_category_id = #resolved_View_Name_category_id,
xref_value = #xref_value,
availability_start_date = #availability_start_date,
availability_end_date = #availability_end_date,
status_code = #status_code,
last_mod_user_id = #last_mod_user_id ,
last_mod_timestamp = #CT
Where #sup_id = supplier_id
AND #View_Name_id = View_Name_id
AND shipper_flag = 'n'
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
End
End
UPDATE
merch_ctlg_ipt_event
SET action_code = #done_action_code,
last_mod_timestamp = #CT
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
COMMIT TRAN
Return
go
Could you please help ?
You have 2 commas in a row here
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
Also probably not relevant to the error message but you have a line
Where #sup_id = supplier_id
but the declared variable is #supplier_id