# Issues running namedqueries from script

**URL:** <https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544>\
**Category:** Ignition\
**Tags:** namedqueries, scripting\
**Created:** [January 29, 2025, 10:42am UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544 "2025-01-29T10:42:47Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Morten\_Jepsen](https://avatars.discourse-cdn.com/v4/letter/m/a587f6/32.png) [@Morten\_Jepsen](https://forum.inductiveautomation.com/u/Morten_Jepsen)\
**Post date:** [January 29, 2025, 10:42am UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/1 "2025-01-29T10:42:47Z")

</div>

I have a script that is causing me some issues. I need it to run 2 sql queries depending on the value of the tag it is connected to.  
First issue is running the query. When i comment in the syste.db.runNamedQuery, it fails, and it doesnt write to the other tags. It works when the query isnt used. When running the parameter and system.db.runNamedQuery from the script console it works fine.

 ![image](https://us1.discourse-cdn.com/inductiveautomation/original/3X/2/8/285e8f18f2ecc83785201bd38016e7dc6d2b8a8b.png)

Another this is using the currentValue in the definition. I cant get that to work either, and have to read in the value with readBlocking, but it should be the same value as its the same tag.

```python
def valueChanged(tag, tagPath, previousValue, currentValue, initialChange, missedEvents):
    result = system.tag.readBlocking("[default]ongoingStop[0].value")
    result = currentValue
    ongoing = result[0].value
    #result = system.tag.readBlocking("[default]Counter 1")
    result = currentValue
    counterVal = result[0].value
    stop_time = system.date.now()
    
    if counterVal < 100 and not initialChange and not ongoing:  
        # Create a python dictionary of parameters to pass
        parameters = {"startTime": stop_time, "reason": 1, "stopType": 1, "line": 1}
        # Run Named Query
        #system.db.runNamedQuery("Create Stop", parameters)
        system.tag.writeBlocking("[default]ongoingStop", [True])
        system.tag.writeBlocking("[default]TestInt", counterVal)
    elif counterVal > 100 and not initialChange and ongoing:    	 
    	 # Create a python dictionary of parameters to pass
		parameters = {"stopTime": stop_time, "line": 1}
        # Run Named Query
        #namedQuery = "Stop Stop"
        #system.db.runNamedQuery(namedQuery, parameters)
		system.tag.writeBlocking("[default]ongoingStop", [False])
		system.tag.writeBlocking("[default]TestInt", counterVal)

```

---

<div class="post-metadata">

**Author:** ![Transistor](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/transistor/32/3380_2.png) [@Transistor](https://forum.inductiveautomation.com/u/Transistor)\
**Post date:** [January 29, 2025, 11:27am UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/2 "2025-01-29T11:27:33Z")

</div>

Welcome to the forum, Morten.

Your code has a lot of experimentation left in it that needs to be cleaned out.

- You have set the value of `result` three times.
- The lines below don't look right. `currentValue` isn't an array as far as I can see.

```python
    result = currentValue
    ongoing = result[0].value

```

- What is the SQL datatype for `startTime`. I'd expect it to be DATETIME but you're passing in "test" in your Script Console screen grab.
- `system.tag.writeBlocking` is expecting a list for the tagpaths and a list for the parameters. (It will work with only one item for backwards compatibility but don't rely on it not to change.)
- You should combine all your `system.tag.writeBlocking` lines into one (in each `if` branch).

Clean up the code and redefine the problem and you'll get help.

It might be a good idea to post the formatted code of the named queries also.

---

<div class="post-metadata">

**Author:** ![michael.flagler](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/michael.flagler/32/26272_2.png) [@michael.flagler](https://forum.inductiveautomation.com/u/michael.flagler)\
**Post date:** [January 29, 2025, 12:26pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/3 "2025-01-29T12:26:11Z")

</div>

Also, make sure you're reading from the right tag at the beginning. Is ongoingStop an array or a single tag? If it's a single tag, you could simplify this to:

```python
counterVal = system.tag.readBlocking(["[default]ongoingStop"])[0].value

```

---

<div class="post-metadata">

**Author:** ![pturmel](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/pturmel/32/3295_2.png) [@pturmel](https://forum.inductiveautomation.com/u/pturmel)\
**Post date:** [January 29, 2025, 1:42pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/4 "2025-01-29T13:42:21Z")

</div>

Named query functions have a different required set of arguments when used in gateway scope (like tag events) versus Vision Client scope (which is what you have in the designer script console). Take a closer look at the documentation.

---

<div class="post-metadata">

**Author:** ![Benjamin\_Furlani](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/benjamin_furlani/32/66084_2.png) [@Benjamin\_Furlani](https://forum.inductiveautomation.com/u/Benjamin_Furlani)\
**Post date:** [January 29, 2025, 1:51pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/5 "2025-01-29T13:51:03Z")

</div>

I also think it is worth mentioning, as it is all over the forum, you shouldn't do long running processes in value change scripts like run named queries etc. as it can cause missed events to happen.

---

<div class="post-metadata">

**Author:** ![Morten\_Jepsen](https://avatars.discourse-cdn.com/v4/letter/m/a587f6/32.png) [@Morten\_Jepsen](https://forum.inductiveautomation.com/u/Morten_Jepsen)\
**Post date:** [January 29, 2025, 3:07pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/6 "2025-01-29T15:07:34Z")

</div>

> [@michael.flagler](#):
>
> `counterVal = system.tag.readBlocking(["[default]ongoingStop"])[0].value`

Ahh thanks. I had the syntax wrong when trying that, hence the workaround =) Havent worked alot with Python, mostly the C#/C++.

---

<div class="post-metadata">

**Author:** ![Morten\_Jepsen](https://avatars.discourse-cdn.com/v4/letter/m/a587f6/32.png) [@Morten\_Jepsen](https://forum.inductiveautomation.com/u/Morten_Jepsen)\
**Post date:** [January 29, 2025, 3:20pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/7 "2025-01-29T15:20:44Z")

</div>

I clean the code, and tested again. It runs without the query's but not when commented in. Counter 1 and ongoingStop are a simple int and bool.

Named Update Query:

```python
INSERT INTO Stops
	(startTime, stopTime, registrered, reason, stopType, line)
VALUES
	(:startTime, "Igangværende", FALSE, :reason, :stopType, :line)

```

With a string parameter for :startTime and a Int1 for :reason, :stopType, :line.

```python
def valueChanged(tag, tagPath, previousValue, currentValue, initialChange, missedEvents):
	ongoing = system.tag.readBlocking("[default]ongoingStop")[0].value
	counterVal = system.tag.readBlocking("[default]Counter 1")[0].value
	stop_time = system.date.now()
    
	if counterVal < 100 and not initialChange and not ongoing:  
		# Create a python dictionary of parameters to pass
		parameters = {"startTime": stop_time, "reason": 1, "stopType": 1, "line": 1}
		# Run Named Query
		system.db.runNamedQuery("Create Stop", parameters)
		system.tag.writeBlocking("[default]ongoingStop", [True])
	elif counterVal > 100 and not initialChange and ongoing:    	 
		# Create a python dictionary of parameters to pass
		parameters = {"stopTime": stop_time, "line": 1}
		# Run Named Query
		#namedQuery = "Stop Stop"
		#system.db.runNamedQuery(namedQuery, parameters)
		system.tag.writeBlocking("[default]ongoingStop", [False])

```

---

<div class="post-metadata">

**Author:** ![dillon](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/dillon/32/81537_2.png) [@dillon](https://forum.inductiveautomation.com/u/dillon)\
**Post date:** [January 29, 2025, 3:25pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/8 "2025-01-29T15:25:50Z")

</div>

Can you share the error information from the log or the error pop-up that happens in the designer? There are a few things that could be happening between SQL type conflictions or constraints requiring stopTime column to have data on row insertion. Transistor already alluded to this.

> [@Transistor](#):
>
> What is the SQL datatype for `startTime`. I'd expect it to be DATETIME but you're passing in "test" in your Script Console screen grab.

Did you try running the same SQL query with the parameters directly in a SQL GUI or CLI to make sure that the query matches the table structure?

---

<div class="post-metadata">

**Author:** ![YF129701](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/yf129701/32/60498_2.png) [@YF129701](https://forum.inductiveautomation.com/u/YF129701)\
**Post date:** [January 29, 2025, 3:36pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/9 "2025-01-29T15:36:28Z")

</div>

I see a few issues... Are you sure your `registered` column is called `registrered` in the database? If so, you should fix it, if possible.

Otherwise, here are some more improvements to your code:

```python
def valueChanged(tag, tagPath, previousValue, currentValue, initialChange, missedEvents):
	# read tags all at once
	tags = system.tag.readBlocking(["[default]ongoingStop", "[default]Counter 1"])
	ongoing = tags[0].value
	counterVal = tags[1].value
	stop_time = system.date.now()
    
	if counterVal < 100 and not initialChange and not ongoing:  
		# Create a python dictionary of parameters to pass
		parameters = {"startTime": stop_time, "reason": 1, "stopType": 1, "line": 1}
		# Run Named Query
		system.db.runNamedQuery("Create Stop", parameters)
		# if you use array syntax for values, also use array syntax for tagPaths
		system.tag.writeBlocking(["[default]ongoingStop"], [True])
	elif counterVal > 100 and not initialChange and ongoing:    	 
		# Create a python dictionary of parameters to pass
		parameters = {"stopTime": stop_time, "line": 1}
		# Run Named Query
		namedQuery = "Stop Stop"
		system.db.runNamedQuery(namedQuery, parameters)
		# same thing here... tagPaths and tagValues are both lists
		system.tag.writeBlocking(["[default]ongoingStop"], [False])

```

As I mention in the comments, if you use the array syntax for `system.tag.writeBlocking`, use it consistently. I feel that what you're doing would result in an exception being thrown (although I'm not sure if you're even getting to that point if the query isn't executing).

What I mean is that either do `system.tag.writeBlocking([""], [""])` or `system.tag.writeBlocking("", "")`, but not what you had: `system.tag.writeBlocking("", [""])`.

Also, as @dillon mentioned above, make sure the query works when you run it from the script console.

---

<div class="post-metadata">

**Author:** ![pturmel](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/pturmel/32/3295_2.png) [@pturmel](https://forum.inductiveautomation.com/u/pturmel)\
**Post date:** [January 29, 2025, 3:43pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/10 "2025-01-29T15:43:42Z")

</div>

> [@YF129701](#):
>
> make sure the query works when you run it from the script console.

> [@Morten\_Jepsen](#):
>
> When running the parameter and system.db.runNamedQuery from the script console it works fine.

The OP hasn't followed my instructions yet. The problem is the difference between gateway scope and Vision Client scope (designer).

Other notes:

- Use a single `readBlocking()`. Like this, perhaps:

```python
	ongoing, counterVal = [qv.value for qv in system.tag.readBlocking(["[default]ongoingStop", "[default]Counter 1"])]

```

- `writeBlocking()` is **not safe** in tag events unless the tag is a memory tag. Use `writeAsync()` if you cannot use a gateway tag change event (in the project, not on the tag).

- `runNamedQuery()` is **not safe** in tag events. Use `runSFNamedQuery()` or move your entire event to a gateway tag change event.

---

<div class="post-metadata">

**Author:** ![Jay\_Baker](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/jay_baker/32/35448_2.png) [@Jay\_Baker](https://forum.inductiveautomation.com/u/Jay_Baker)\
**Post date:** [February 16, 2025, 8:33pm UTC](https://forum.inductiveautomation.com/t/issues-running-namedqueries-from-script/101544/11 "2025-02-16T20:33:43Z")

</div>

I'm sure you've probably solved this by now, but for future reference, you just need to run the named query with named parameters. This gets around the difference in required parameters for the different contexts. Eg:

```python
system.db.runNamedQuery(
			project=system.project.getProjectName(), 
			path='Materials_Q/Config/getPlantsAndTests', 
			parameters={},
		)

```
