Query coding with Dynamic Column naming

Hi guys,

I’m trying to get the contents in a certain column referring to the name of the row in a table. My code is following:

def valueChanged(tag, tagPath, previousValue, currentValue, initialChange, missedEvents):
	Target_Column_SQL = "[.]Station_ID"
	Name = "[.]Name"
	Trainer = "[.]Trainner_Log_In"
	Level = "[.]Training_Level"
	sourceTagPath = "[.]Badge"
	database = 'DW_SCADA_MSSQL'
	
	badgeRead = system.tag.readBlocking([sourceTagPath])[0].value
	target = system.tag.readBlocking([Target_Column_SQL])[0].value
	
	ReadResult = []
	
	if currentValue.value != "0":
		query = "SELECT Badge, employee_name, [{0}]] FROM Training_Matrix WHERE Badge = ?".format(target)
		ReadResult = system.db.runPrepQuery(query, [badgeRead], database)
		
	if ReadResult:
		system.tag.writeBlocking([Name], [ReadResult[0][1]])
		system.tag.writeBlocking([Level], [ReadResult[0][2]])

		if ReadResult[0][1] in ('Khuc, Hoa The', 'Osorno, Hector', 'Imafidon-Taiwo, Shogbolu', 'Janapareddy, Sreedhar'):
			system.tag.writeBlocking([Trainer], [True])
	else:
		system.tag.writeBlocking([Name], ["User Not Found"])


		system.tag.writeBlocking([Level], [""])

The script attached to a child tag to my UDT as following:

For some reason the script would not work as I expected.

But when I remove the dynamic element [{0}] and .format(target) then replace with solid name “WL_OP10_30“ in the following code, the script works.

query = "SELECT Badge, employee_name, [{0}]] FROM Training_Matrix WHERE Badge = ?".format(target)
query = "SELECT Badge, employee_name, WL_OP10_30 FROM Training_Matrix WHERE Badge = ?"

Can anyone give me some clue?

**Sorry for the confusing if the layout doesn't make sense.

I don't understand the syntax, but have you an error in [{0}]]?
The square bracket counts are different.

It is unsafe to run database queries in tag valueChange() event scripts. (Only updates through the S&F subsystem are safe.) Move all of this code to a gateway tag change event script (project, not on a tag).

Anything that might cause a script to take more than a handful of milliseconds risks locking up all tag event scripting.

Sorry that was a mistake. I have removed it but nothing changes

Thank you for the reply, it’s good to know. I have moved all these code to script gatway event, but it still doesn't work.

Btw, I have another tag with the same code in tag valuechange event, and it works fine. The different between these 2 tags are the data type. The one with script working is an individual OPC tag, while the one has the problem is one of the child tag of a UDT which contains a few tags in different data type

Unrelated, but you also should not be reading and writing to single tags sequentially with multiple calls to system.tag.*; multiple reads/writes should always be done in a single call by supplying a list, for efficiency, otherwise you're building artificial scalability limits into your application

Can you share the error from the logs?