I have a sample stored procedure in Snowflake where it does the below steps one after the other
Insert Metadata with start details
Get the total count of table which is passed as argument
Update Metadata with success/failure
Issue here is When the given table name doesn't exist on database, The stored procedure exits with error however its not updating the Metadata with error details and the Metadata entry shows status as "In-Progress" while the stored procedure failed at point #2.
I'm looking for a clean exit when the table doesn't exist in database then stored procedure should update metadata with error details and exit cleanly.
Can someone have a look on below code and suggest if I'm missing something here please. I'm new to snowflake and procedure's as well. Thanks.
CREATE OR REPLACE PROCEDURE abc.PROC_GET_COUNT(table_name varchar)
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS $$
// SQL Queries
var get_execution_id_sql = "select t.nextval from table(getnextval(EXECUTION_SEQUENCE)) t";
var get_count_sql = `select count(*) from abc.`+ TABLE_NAME +;
var result_set1 = snowflake.createStatement({sqlText: get_execution_id_sql}).execute();
result_set1.next();
var seq_num= result_set1.getColumnValue(1);
var insert_meta_sql1= `INSERT into abc.ERROR_LOG (EXECUTION_ID, STATUS, START_TS) values ( '` +seq_num+ `', 'In_Progress', CURRENT_TIMESTAMP)`;
try {
message = 'In insert Metadata with start details';
snowflake.execute({sqlText: insert_meta_sql1});
message = 'In Process of get count';
get_count_out = snowflake.execute ({sqlText: get_count_sql});
get_count_out.next();
rec_count = get_count_out.getColumnValue(1);
upd_meta_sql = `UPDATE abc.ERROR_LOG SET END_TS = current_timestamp, STATUS = 'SUCCESS', MESSAGE = '` + TABLE_NAME + ` - Total count: ` + rec_count + `' where EXECUTION_ID = '` + seq_num + `';
message = 'In update Metadata with end details';
snowflake.execute ({sqlText: upd_meta_sql});
} catch (err) {
upd_meta_sql = `UPDATE abc.ERROR_LOG SET
END_TS = current_timestamp,
STATUS = 'FAILED',
MESSAGE = '` + message + `. Error Details -- \n Code: `+ err.code +`\n State: `+ err.state +`\n Message: `+ err.message +`\n Stack Trace: `+ err.stackTraceTxt +`'
where EXECUTION_ID = '` + seq_num + `';
snowflake.execute ({sqlText: upd_meta_sql});
return "Failed: " + message + ' -- ' +err;
}
return 'SUCCESS';
$$;
There are some syntax errors in the sample code, but I assume that all of them are caused when you are copying the script here. The main issue is err.message contains text with single quote characters which breaks the last SQL.
Here is the scripts for my test environment (it would be very helpful for others if you share yours when asking a question which needs debugging):
create schema abc;
create table deneme ( id number ) as select seq4()
from table(generator(rowcount=>100));
create or replace table ERROR_LOG (EXECUTION_ID number,
MESSAGE varchar, STATUS varchar, START_TS timestamp , END_TS timestamp);
create or replace sequence seq1;
Here is the fixed version of the procedure:
CREATE OR REPLACE PROCEDURE abc.PROC_GET_COUNT(table_name varchar)
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS $$
var get_execution_id_sql = "select t.nextval from table(getnextval(seq1)) t";
var get_count_sql = `select count(*) from abc.`+ TABLE_NAME ;
var result_set1 = snowflake.createStatement({sqlText: get_execution_id_sql}).execute();
result_set1.next();
var seq_num= result_set1.getColumnValue(1);
var insert_meta_sql1= `INSERT into abc.ERROR_LOG (EXECUTION_ID, STATUS, START_TS) values ( ` + seq_num + `, 'In_Progress', CURRENT_TIMESTAMP)`;
try {
message = 'In insert Metadata with start details';
snowflake.execute({sqlText: insert_meta_sql1});
message = 'In Process of get count';
get_count_out = snowflake.execute ({sqlText: get_count_sql});
get_count_out.next();
rec_count = get_count_out.getColumnValue(1);
upd_meta_sql = `UPDATE abc.ERROR_LOG SET END_TS = current_timestamp, STATUS = 'SUCCESS', MESSAGE = '` + TABLE_NAME + ` - Total count: ` + rec_count + `' where EXECUTION_ID = '` + seq_num +`'`;
message = 'In update Metadata with end details';
snowflake.execute ({sqlText: upd_meta_sql});
} catch (err) {
upd_meta_sql = `UPDATE abc.ERROR_LOG SET
END_TS = current_timestamp,
STATUS = 'FAILED',
MESSAGE = '` + message + `. Error Details -- \n Code: `+ err.code +`\n State: `+ err.state +`\n Message: `+ err.message.replace( /'/g , "''" ) +`\n Stack Trace: `+ err.stackTraceTxt +`'
where EXECUTION_ID = '` + seq_num + `'`;
snowflake.execute ({sqlText: upd_meta_sql});
return "Failed: " + message + ' -- ' +err;
}
return 'SUCCESS';
$$;
As you may notice, I used err.message.replace( /'/g , "''" ) instead of err.message when generating the SQL.
call PROC_GET_COUNT( 'deneme' ); -- succesful as the table exits
call PROC_GET_COUNT( 'deneme21' ); -- shows error
This is the content of the message column of second try:
In Process of get count. Error Details --
Code: 100183
State: P0000
Message: SQL compilation error:
Object 'GOKHAN_DB.ABC.DENEME21' does not exist or not authorized.
Stack Trace: At Snowflake.execute, line 20 position 30
I see the issue has to do with single quotes being returned in the error message.
I recommend, setting the message variable. While you are writing shorter code, its more cryptic and harder to find the issue.
By breaking the code down into simpler steps you will find the issue easier.
CREATE OR REPLACE SCHEMA abc;
USE SCHEMA ABC;
CREATE SEQUENCE IF NOT EXISTS EXECUTION_SEQUENCE
WITH
START WITH = 1
INCREMENT BY = 1
COMMENT = 'DEMO SEQUENCE ' ;
CREATE OR REPLACE TABLE abc.ERROR_LOG(EXECUTION_ID number , STATUS varchar, MESSAGE VARCHAR, START_TS timestamp_ltz , END_TS timestamp_ltz);
CREATE TABLE ABC.TEST_TABLE1(ID NUMBER, MESSAGE VARCHAR);
INSERT INTO ABC.TEST_TABLE1(ID, MESSAGE)
SELECT SEQ4() + 1 , RANDSTR(50, RANDOM())
FROM TABLE(GENERATOR(ROWCOUNT=>50));
SELECT * FROM ABC.TEST_TABLE1 ORDER BY 1 ASC;
CREATE OR REPLACE PROCEDURE abc.PROC_GET_COUNT(table_name varchar)
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS $$
// SQL Queries
var get_execution_id_sql = "select t.nextval from table(getnextval(EXECUTION_SEQUENCE)) t";
var get_count_sql = `select count(*) from abc.`+ TABLE_NAME +`;`
var result_set1 = snowflake.createStatement({sqlText: get_execution_id_sql}).execute();
result_set1.next();
var seq_num= result_set1.getColumnValue(1);
var insert_meta_sql1= `INSERT into abc.ERROR_LOG (EXECUTION_ID, STATUS, START_TS,MESSAGE) values ( '` +seq_num+ `', 'In_Progress', CURRENT_TIMESTAMP(), '`+TABLE_NAME+`')`;
try {
message = 'In insert Metadata with start details';
snowflake.execute({sqlText: insert_meta_sql1});
message = 'In Process of get count';
get_count_out = snowflake.execute ({sqlText: get_count_sql});
get_count_out.next();
rec_count = get_count_out.getColumnValue(1);
upd_meta_sql = `UPDATE abc.ERROR_LOG SET END_TS = current_timestamp(), STATUS = 'SUCCESS', MESSAGE = '` + TABLE_NAME + ` - Total count: ` + rec_count + `' where EXECUTION_ID = ` + seq_num + `;`
message = 'In update Metadata with end details';
snowflake.execute ({sqlText: upd_meta_sql});
} catch (err) {
message = `Error Details\r\nCode: ` + err.code + `\r\nState:` + err.state +`\r\nMessage: ` + err.message + `\r\nStack Trace: ` + err.stackTraceTxt;
// **** you need to replace the single quotes that are being returned in your error message
message = message.replace(/'/g, `"`);
upd_meta_sql = `UPDATE abc.ERROR_LOG
SET END_TS = current_timestamp()
,STATUS = 'FAILED'
, MESSAGE = '` + message +`' where EXECUTION_ID = ` + seq_num + `;`
snowflake.execute ({sqlText: upd_meta_sql});
return "Failed: " + message + ' -- ' +err;
}
return 'SUCCESS';
$$;
CALL abc.PROC_GET_COUNT('TEST_TABLE1');
CALL abc.PROC_GET_COUNT('TEST_TABLE_MISSING');
SELECT * FROM abc.ERROR_LOG ORDER BY 1 ASC;
Solution is here:
Related
I have written down a procedure by following the snowflake documentation to generate a list of 'SET' statement and execute them in Snowflake. I'm getting Unexpected identifier error while calling the procedure. could somebody please help me out here.
create or replace procedure SET_ENV()
returns string
language JavaScript
as
$$
MASTER_QUERY = {sqlText: SELECT ('SET '||TABLE_NAME||'=
CONCAT($Database_pre,'||'''.'''||',$Schema_pre,'||'''.'''||','''||TABLE_NAME||''');') AS
QUERY
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
AND( TABLE_NAME NOT LIKE 'TMP_%' AND TABLE_NAME NOT LIKE '%WRK_%')};
STATEMENT = snowflake.createStatement(MASTER_QUERY);
rs = STATEMENT.execute();
var s = '';
while (rs.next()) {
EXECUTION_QUERY = {sqlText: rs.getColumnValue("QUERY")};
stmtEx = snowflake.createStatement(EXECUTION_QUERY);
stmtEx.execute();
s += rs.getColumnValue(1) + "\n";
}
return s;
$$
;
CALL SET_ENV()
The error i'm getting is as follows.
JavaScript compilation error: Uncaught SyntaxError: Unexpected identifier in SET_ENV at 'MASTER_QUERY = {sqlText: 'SELECT ('SET '||TABLE_NAME||'= ' position 35
I'm able to run it after I add backtick (`) characters to enclose the SQL command:
create or replace procedure SET_ENV()
returns string
language JavaScript
execute as CALLER
as
$$
MASTER_QUERY = {sqlText: `SELECT ('SET '||TABLE_NAME||'=
CONCAT($Database_pre,'||'''.'''||',$Schema_pre,'||'''.'''||','''||TABLE_NAME||''');') AS
QUERY
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
AND( TABLE_NAME NOT LIKE 'TMP_%' AND TABLE_NAME NOT LIKE '%WRK_%')` };
STATEMENT = snowflake.createStatement(MASTER_QUERY);
rs = STATEMENT.execute();
var s = '';
while (rs.next()) {
EXECUTION_QUERY = {sqlText: rs.getColumnValue("QUERY")};
stmtEx = snowflake.createStatement(EXECUTION_QUERY);
stmtEx.execute();
s += rs.getColumnValue(1) + "\n";
}
return s;
$$;
set DATABASE_PRE='DBPRE';
set Schema_pre = 'SCHPRE';
call SET_ENV();
Important: You should also define the procedure as "execute as CALLER" to be able to access session variables. I suggest you define arguments instead of accessing session variables.
I'm working with a SQL Server stored procedure in Classic ASP with 3 parameters. I am attempting to find the recordcount, but it returns '-1'.
I saw a similar post, did what it suggested (check cursortype, and add 'set nocount on' in the stored procedure), but those changes did not impact the -1 recordcount.
Here is my code in the Classic ASP page, below.
strInterestName = request("InterestName")
strActiveDate = request("activedate")
strExpireDate = request("expiredate")
Set objCommandSec = CreateObject("ADODB.Command")
Set objRS = CreateObject("ADODB.RecordSet")
objRS.cursorlocation = 3
objRS.cursortype = adOpenStatic
With objCommandSec
Set .ActiveConnection = objConnection
.CommandText = "[01_cms_search_pg_select_news_items_4]"
.CommandType = 4
.Parameters.Append .CreateParameter("#InterestName",adVarChar,
adParamInput, 25)
.Parameters.Append .CreateParameter("#ActiveDate",adDate, adParamInput)
.Parameters.Append .CreateParameter("#ExpireDate",adDate,
adParamInput)
.Parameters("#InterestName") = strInterestName
.Parameters("#ActiveDate") = strActiveDate
.Parameters("#ExpireDate") = strExpireDate
set objRS =.Execute()
End With
Here is the code for the stored procedure, below:
ALTER PROCEDURE [dbo].[01_cms_search_pg_select_news_items_4]
#InterestName varchar(50),
#ActiveDate datetime,
#ExpireDate datetime
AS DECLARE #sql nvarchar(4000)
SELECT #sql = ' SELECT * ' +
' FROM news ' +
' WHERE ' +
' bulletin_display_indicator = ''true'' '+
' AND ' +
' website_homepg_display_indicator= ''false'' '
IF #InterestName is not null
SELECT #sql = #sql + ' AND (InterestName = #InterestName)
IF #ExpireDate is not null and #ExpireDate IS NOT NULL
SELECT #sql = #sql + ' AND (expiredate between #ActiveDate and #ExpireDate)
SELECT #sql = #sql + '; '
EXEC sp_executesql #sql, N'#InterestName varchar(50), #ActiveDate
DateTime, #ExpireDate DateTime',#InterestName, #ActiveDate,
#ExpireDate
I struggled with that for a while, then found something that works for me.
It's not pretty but it does the job.
Have your Stored Procedure return 2 recordsets: one with the table data you need followed by one with the recordcount:
SELECT <all_you_need> FROM <your_table> WHERE <your_arguments>
SELECT [myCount] = ##ROWCOUNT
Then, in your ASP file:
dim objRS, dataRS, countRS
Set objRS = CreateObject("ADODB.RecordSet")
Set dataRS = CreateObject("ADODB.RecordSet")
Set countRS = CreateObject("ADODB.RecordSet")
[your original call to the stored procedure]
set objRS =.Execute()
set dataRS = objRS
set countRS = objRS.nextrecordset()
countRS now contains a recordset with a single row and a single column named 'myCount' that you can query to get the recordcount.
dataRS contains your original dataset.
NOTE: if you don't need to know the recordcount BEFORE you process the dataset, you can simplify like this:
dim objRS, countRS
Set objRS = CreateObject("ADODB.RecordSet")
Set countRS = CreateObject("ADODB.RecordSet")
[your original call to the stored procedure]
set objRS =.Execute()
[process your dataset as you need to]
set countRS = objRS.nextrecordset()
Background: SQL Server 2008 R2
Having issues with the following. Been given a usp to "finish off", author is unavailable. It extracts data from source table, copies to target table of same name + datetime stamp in an archive db then truncates source table. Want to confirm that no errors have occurred & row counts are the same before I truncate source. As I'm using DDL a TRY CATCH combo won't work.
Following code works:
DECLARE #HostName VARCHAR(30) -- Name of server running script
DECLARE #dbName VARCHAR(30) -- Database currently connected to
DECLARE #LogText VARCHAR(255) -- Text to be logged to ArchLog table
DECLARE #NewUTMetaData VARCHAR(255) -- New tablename for UTMetaData
DECLARE #NewOutboundMessagePending VARCHAR(255) -- New tablename for OutboundMessagePending
DECLARE #NewOutboundMessageStatus VARCHAR(255) -- New tablename for OutboundMessageStatus
DECLARE #NewOutboundMessageResult VARCHAR(255) -- New tablename for OutboundMessageResult
DECLARE #NewFileMessageNonSequence VARCHAR(255) -- New tablename for FileMessageNonSequence
DECLARE #NewOutboundMessageRequest VARCHAR(255) -- New tablename for OutboundMessageRequest
DECLARE #NewOutboundMessage VARCHAR(255) -- New tablename for OutboundMessage
DECLARE #SQLQuery NVARCHAR(500)
DECLARE #return_value INT
DECLARE #Err INT = 0
DECLARE #ErrFin INT = 0
DECLARE #SQLCount NVARCHAR(255) = 'SELECT #TargetCountOUT = COUNT(*) FROM '
DECLARE #ParmDefinition nvarchar(50) = N'#TargetCountOUT int OUTPUT';;
DECLARE #SourceCount INT = 0
DECLARE #TargetCount INT = 0
-- Log message that delete is starting
SELECT #HostName = host_name()
SELECT #dbName = db_name()
SELECT #LogText = 'Procedure ArchiveMuleDBMetrix_NEW starting database= ' + #dbname + ' host= ' + #HostName
EXEC xp_logevent 50001, #LogText, 'INFORMATIONAL'
INSERT INTO [MuleDBArch].[dbo].[ArchLog]
([LogEntryDateTime]
,[LogEntry])
VALUES (GETDATE()
,#LogText)
BEGIN
SELECT #NewUTMetaData = (SELECT '[MuleDBArch].[dbo].UTMetaDataA' + convert(varchar(50),GetDate(),112) + replace(convert(varchar, GetDate(),108),':',''))
SET #err = ##error;
SET #SQLQuery = 'select * into ' + #NewUTMetaData + ' from [MuleDB].[dbo].[SASITUTMetaData]'
EXECUTE sp_executesql #SQLQuery
SET #SourceCount = ##ROWCOUNT
SELECT #LogText = 'Rows archived into ' + #NewUTMetaData + ' by Procedure ArchiveMuleDBMetrix_NEW = ' + CAST(#SourceCount as VARCHAR(6))
EXEC xp_logevent 50002, #LogText, 'INFORMATIONAL'
INSERT INTO [MuleDBArch].[dbo].[ArchLog]
([LogEntryDateTime]
,[LogEntry])
VALUES (GETDATE()
,#LogText)
IF #err = 0
BEGIN
SET #sqlcount = #sqlcount + #NewUTMetaData
EXECUTE sp_executesql #sqlcount, #ParmDefinition, #TargetCountOUT=#TargetCount OUTPUT;
IF #SourceCount = #TargetCount
TRUNCATE TABLE [MuleDB].[dbo].[SASITUTMetaData]
ELSE
SELECT #LogText = 'Post archive, row counts differ between [MuleDB].[dbo].[SASITUTMetaData] and' + #NewUTMetaData
EXEC xp_logevent 50003, #LogText, 'Error'
Set #errfin = 1
SET #err = 0
END
ELSE
BEGIN
SELECT #LogText = 'Procedure ArchiveMuleDBMetrix_NEW failed archiving into ' + #NewUTMetaData
EXEC xp_logevent 50004, #LogText, 'Error'
Set #errfin = 1
SET #err = 0
END
END
However, if I repeat the block to work on another table (or indeed the same one) query completes with error and I get the message:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
I think I've narrowed it down to the line:
EXECUTE sp_executesql #sqlcount, #ParmDefinition, #TargetCountOUT=#TargetCount OUTPUT;
Any help appreciated
In the below code
EXECUTE sp_executesql #sqlcount, #ParmDefinition, #TargetCountOUT=#TargetCount OUTPUT;
You are trying to pass parameter values without specifying the parameter names except the output parameter while calling the stored procedure. Either specify the parameter name for all or none. Try to execute the code as follows
EXECUTE sp_executesql #sqlcount, #ParmDefinition, #TargetCount OUTPUT;
Issue:
The database is not updating but I'm unsure where it drops.
I've used numerous ones in the past but I can't see why this is not working. If I could see how to run an error test on the stored procedure I suspect that would help.
Tests:
I pass the variables to a label, after the stored procedure request in the .aspx code to check the values exist (left in code)
Change int to varchar in the stored procedure
Query:
How do I fix this and then how can I run tests to find the issues in the future
Stored Procedure:
USE [DATABASE]
GO
/****** Object: StoredProcedure [dbo].[spChangeValue] Script Date: 11/08/2015 12:02:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER PROCEDURE [dbo].[spRiskRatingChange]
#ActionID int,
#EmployeeID int,
#NewRating varchar(10)
AS
DECLARE #DateChanged AS nvarchar(max)
SET #DateChanged = GETDATE()
DECLARE #OldRating AS nvarchar(max)
DECLARE #OldComments AS nvarchar(max)
DECLARE #EmployeeName AS nvarchar(max)
SET #OldRating =
(
SELECT OverallRiskCategory FROM TblAsbestos WHERE ID = #ActionID
)
SET #OldComments =
(
SELECT Comments FROM TblAsbestos WHERE ID = #ActionID
)
SET #EmployeeName =
(
SELECT UserFirstName + ' ' + UserSurname FROM SystemUsers WHERE ID = #EmployeeID
)
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE TblAsbestos SET OverallRiskCategory = #NewRating, RiskCategory = #NewRating,
Comments= ('Rating changed from ' + RTRIM(#OldRating) + ' to '
+ RTRIM(#NewRating) + 'By ' + #EmployeeName + ' on ' + #DateChanged + ' -- ' + #OldComments)
WHERE ID = #ActionID
END
Code in .aspx.vb
Dim connection As SqlConnection
Dim command As New SqlCommand
Dim ds As New DataSet
Dim ConnectionString1 As String = System.Configuration.ConfigurationManager.ConnectionStrings("VINCI_SQL").ToString()
connection = New SqlConnection(ConnectionString1)
connection.Open()
With command
.Connection = connection
.CommandText = "spRiskRatingChange" 'include audit names
.CommandType = CommandType.StoredProcedure
.Parameters.Clear()
.Parameters.AddWithValue("#ActionID", Session("ActionID").ToString)
.Parameters.AddWithValue("#EmployeeID", Session.Item("EmployeeID").ToString)
.Parameters.AddWithValue("#NewRating", ddOverallRiskCategoryEdit.SelectedValue)
.ExecuteNonQuery()
lblErrorMessageRatings.Visible = True
lblErrorMessageRatings.Text = "Action ID: " & Session("ActionID").ToString
lblErrorMessageRatings.Text = lblErrorMessageRatings.Text & " EmployeeID: " & Session("EmployeeID").ToString
lblErrorMessageRatings.Text = lblErrorMessageRatings.Text & " NewRating: " & ddOverallRiskCategoryEdit.SelectedValue
Read items such as:
UPDATE Stored Procedure not Updating
Instead of
.Parameters.AddWithValue("#ActionID", Session("ActionID").ToString)
try
.Parameters.Add("#ActionId",SqlDbType.Int)
.Parameters("#ActionId").Value = CInt(Session("ActionId"))
I am assuming it is an int value you are passing
.Parameters.AddWithValue does an implicit type conversion and perhaps this is what is causing your problem
My classic ASP page thorws up an error when I pass 2 paremeters to the Exec code for my
stored procedure. Basically I want to send 1 paremeter to cover the column I am looking for
and one for the search-term. For example imSchool, New York University. I have data checks on the data sent as well as Record Set.State code showing that everytime i choose SQL Query with the two paramerts the error "Operation is not allowed when the object is closed." always shows.
I tried to open the object at " While Not rs.EOF" line of code where it error out bit no luck.
I am thinking my SQLQuery is bad because when I run the Stored Procedure in MSSQL with the same input I get a return table everytime. SQL Server 2008 R2 and Classic ASP.
HERE IS MY IF STATMENT WITH SQLQUERY CODE (keep in mind the 1st one works fine and data is selected from the DB)
SQLQuery = "Exec sp_vw_InternImport"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.CursorType = 3
rs.Open SQLQuery, OBJdbConnection
If filterColmn <> "" Then
SQlQuery = "Exec sp_vw_InternImport_ColID #LookUpID=N'" + filterID + "'" + ", #LookUpCol=N'" + filterID + "'"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.CursorType = 3
rs.Open SQLQuery, OBJdbConnection
End If
HERE IS MY STORED PROCEDURE CODE
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_vw_InternImport_ColID]
(
#LookUpID nvarchar (255),
#LookUpCol nvarchar (50)
)
AS
SET NOCOUNT ON
BEGIN
IF #LookUpCol = 'imYear'
SELECT * FROM v_InternImport WHERE imYear = #LookUpID
ELSE
IF #LookUpCol = 'imSchool'
SELECT * FROM v_InternImport WHERE imSchool = #LookUpID
ELSE
IF #LookUpCol = 'imDiscipline'
SELECT * FROM v_InternImport WHERE imDiscipline = #LookUpID
IF #LookUpCol = 'imDegree'
SELECT * FROM v_InternImport WHERE imDegree = #LookUpID
END
When passing arguments to stored procedure directly, you don't have to "assign" the parameters. Doing this probably results in the whole value passed (e.g. #LookUpCol will have the value of #LookUpCol ='imYear') thus your SP won't select anything and you have empty and closed recordset.
Try having such code instead:
SQlQuery = "Exec sp_vw_InternImport_ColID '" & filterID & "', '" & filterID & "'"
You can't use the same object twice at the same time (like rs), you have to make it another name or you have to close it and start over.. This should work:
SQLQuery = "Exec sp_vw_InternImport"
If filterColmn <> "" Then SQLQuery = "Exec sp_vw_InternImport_ColID #LookUpID=N'" + filterID + "'" + ", #LookUpCol=N'" + filterID + "'"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.CursorType = 3
rs.Open SQLQuery, OBJdbConnection
rs.Close
Or in your example, if you close the first rs object before you go on to the next, it may help.
set rs = nothing ... then .... set rs = server.createobject
So like this:
SQLQuery = "Exec sp_vw_InternImport"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.CursorType = 3
rs.Open SQLQuery, OBJdbConnection
rs.Close ------ Close it before you re-open it
If filterColmn <> "" Then
SQlQuery = "Exec sp_vw_InternImport_ColID #LookUpID=N'" + filterID + "'" + ", #LookUpCol=N'" + filterID + "'"
rs.Open SQLQuery, OBJdbConnection
rs.Close ------ Always Close your Objects!
End If